entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "0.0.0'\ndescription: 'sike css0to1 day 1'\nauthor: 'FooTearth <footearth@gmail.com>'\nmain: 'mainfile'\nlicense: ", "end": 112, "score": 0.9955465197563171, "start": 103, "tag": "USERNAME", "value": "FooTearth" }, { "context": "ription: 'sike css0to1 day 1'\nauthor: 'FooTearth <footearth@gmail.com>'\nmain: 'mainfile'\nlicense: 'MIT'\nrepository:\n t", "end": 133, "score": 0.9999217391014099, "start": 114, "tag": "EMAIL", "value": "footearth@gmail.com" }, { "context": "ository:\n type: 'git'\n url: 'https://github.com/footearth/sike_css0to1_day_1.git'\nbugs:\n url: 'https://git", "end": 230, "score": 0.869598388671875, "start": 221, "tag": "USERNAME", "value": "footearth" }, { "context": "s0to1_day_1.git'\nbugs:\n url: 'https://github.com/footearth/sike_css0to1_day_1/issues'\nhomepage: 'https://git", "end": 297, "score": 0.9073300361633301, "start": 288, "tag": "USERNAME", "value": "footearth" } ]
npb.cson
footearth/sike_css0to1_day_1
0
# PUBLIC CONFIG name: 'sike_css0to1_day_1' version: '0.0.0' description: 'sike css0to1 day 1' author: 'FooTearth <footearth@gmail.com>' main: 'mainfile' license: 'MIT' repository: type: 'git' url: 'https://github.com/footearth/sike_css0to1_day_1.git' bugs: url: 'https://github.com/footearth/sike_css0to1_day_1/issues' homepage: 'https://github.com/footearth/sike_css0to1_day_1' Keywords: [ 'sike' 'web' 'node' 'gulp' ] # BOWER CONFIG bower: dependencies: [] devDependencies: [] # NPM CONFIG npm: bin: {} scripts: test: '' dependencies: [] devDependencies: [ 'coffee-script' 'npb-coffee' 'lodash' 'del' gulp: [ 'run-sequence' 'gulp-filter' 'gulp-jade' 'gulp-less' 'gulp-tap' 'gulp-watch' 'gulp-plumber' 'browser-sync' ] ] # NPB CONFIG npb: # bower: # root_allow: true npm: commander: 'npm' # default # commander: 'cnpm' # -- build tools -- # build: 'gulp' # default # build: 'grunt'
208830
# PUBLIC CONFIG name: 'sike_css0to1_day_1' version: '0.0.0' description: 'sike css0to1 day 1' author: 'FooTearth <<EMAIL>>' main: 'mainfile' license: 'MIT' repository: type: 'git' url: 'https://github.com/footearth/sike_css0to1_day_1.git' bugs: url: 'https://github.com/footearth/sike_css0to1_day_1/issues' homepage: 'https://github.com/footearth/sike_css0to1_day_1' Keywords: [ 'sike' 'web' 'node' 'gulp' ] # BOWER CONFIG bower: dependencies: [] devDependencies: [] # NPM CONFIG npm: bin: {} scripts: test: '' dependencies: [] devDependencies: [ 'coffee-script' 'npb-coffee' 'lodash' 'del' gulp: [ 'run-sequence' 'gulp-filter' 'gulp-jade' 'gulp-less' 'gulp-tap' 'gulp-watch' 'gulp-plumber' 'browser-sync' ] ] # NPB CONFIG npb: # bower: # root_allow: true npm: commander: 'npm' # default # commander: 'cnpm' # -- build tools -- # build: 'gulp' # default # build: 'grunt'
true
# PUBLIC CONFIG name: 'sike_css0to1_day_1' version: '0.0.0' description: 'sike css0to1 day 1' author: 'FooTearth <PI:EMAIL:<EMAIL>END_PI>' main: 'mainfile' license: 'MIT' repository: type: 'git' url: 'https://github.com/footearth/sike_css0to1_day_1.git' bugs: url: 'https://github.com/footearth/sike_css0to1_day_1/issues' homepage: 'https://github.com/footearth/sike_css0to1_day_1' Keywords: [ 'sike' 'web' 'node' 'gulp' ] # BOWER CONFIG bower: dependencies: [] devDependencies: [] # NPM CONFIG npm: bin: {} scripts: test: '' dependencies: [] devDependencies: [ 'coffee-script' 'npb-coffee' 'lodash' 'del' gulp: [ 'run-sequence' 'gulp-filter' 'gulp-jade' 'gulp-less' 'gulp-tap' 'gulp-watch' 'gulp-plumber' 'browser-sync' ] ] # NPB CONFIG npb: # bower: # root_allow: true npm: commander: 'npm' # default # commander: 'cnpm' # -- build tools -- # build: 'gulp' # default # build: 'grunt'
[ { "context": "-already-exists', 'Token already exists'\n\n\t\tpass = Meteor.uuid()\n\n\t\tloop\n\t\t\tqt = Meteor.users.find({ 'profile.gu", "end": 251, "score": 0.7848718762397766, "start": 240, "tag": "PASSWORD", "value": "Meteor.uuid" }, { "context": "break if not userExists\n\n\t\tuserData =\n\t\t\tusername: user\n\t\t\tpassword: pass\n\n\t\tuserId = Accounts.createUser", "end": 492, "score": 0.9800014495849609, "start": 488, "tag": "USERNAME", "value": "user" }, { "context": "xists\n\n\t\tuserData =\n\t\t\tusername: user\n\t\t\tpassword: pass\n\n\t\tuserId = Accounts.createUser userData\n\n\t\tMeteo", "end": 510, "score": 0.9965147376060486, "start": 506, "tag": "PASSWORD", "value": "pass" }, { "context": "e.token\": token\n\n\t\treturn {\n\t\t\tuser: user\n\t\t\tpass: pass\n\t\t}\n\n\tsendMessageLivechat: (message) ->\n\t\tconsole", "end": 699, "score": 0.9915052652359009, "start": 695, "tag": "PASSWORD", "value": "pass" }, { "context": "models.Rooms.insert\n\t\t\t\t_id: message.rid\n\t\t\t\tname: guest.username\n\t\t\t\tmsgs: 1\n\t\t\t\tlm: new Date()\n\t\t\t\tusern", "end": 1252, "score": 0.6836519241333008, "start": 1247, "tag": "USERNAME", "value": "guest" }, { "context": "Rooms.insert\n\t\t\t\t_id: message.rid\n\t\t\t\tname: guest.username\n\t\t\t\tmsgs: 1\n\t\t\t\tlm: new Date()\n\t\t\t\tusernames: [ o", "end": 1261, "score": 0.5977846384048462, "start": 1253, "tag": "USERNAME", "value": "username" }, { "context": "me\n\t\t\t\tmsgs: 1\n\t\t\t\tlm: new Date()\n\t\t\t\tusernames: [ operator.username, guest.username ]\n\t\t\t\tt: 'd'\n\t\t\t\tts: new Date()\n\t", "end": 1327, "score": 0.9948692321777344, "start": 1310, "tag": "USERNAME", "value": "operator.username" }, { "context": "lm: new Date()\n\t\t\t\tusernames: [ operator.username, guest.username ]\n\t\t\t\tt: 'd'\n\t\t\t\tts: new Date()\n\t\t\t\tv:\n\t\t\t\t\ttoken", "end": 1343, "score": 0.8255118727684021, "start": 1329, "tag": "USERNAME", "value": "guest.username" }, { "context": "ad: 1\n\t\t\t\tu:\n\t\t\t\t\t_id: operator._id\n\t\t\t\t\tusername: operator.username\n\t\t\t\tt: 'd'\n\n\t\troom = Meteor.call 'canAccessRoom',", "end": 1605, "score": 0.9955762028694153, "start": 1588, "tag": "USERNAME", "value": "operator.username" } ]
packages/rocketchat-livechat/methods.coffee
41studio/41chat
1
Meteor.methods registerGuest: (token) -> check token, String user = Meteor.users.findOne { "profile.token": token }, { fields: { _id: 1 } } if user? throw new Meteor.Error 'token-already-exists', 'Token already exists' pass = Meteor.uuid() loop qt = Meteor.users.find({ 'profile.guest': true }).count() + 1 user = 'guest-' + qt userExists = Meteor.users.findOne { 'username': user }, { fields: { _id: 1 } } break if not userExists userData = username: user password: pass userId = Accounts.createUser userData Meteor.users.update userId, $set: name: user "profile.guest": true "profile.token": token return { user: user pass: pass } sendMessageLivechat: (message) -> console.log 'sendMessageLivechat ->',arguments check message.rid, String check message.token, String guest = Meteor.users.findOne Meteor.userId(), fields: username: 1 room = RocketChat.models.Rooms.findOneById message.rid if not room? # find an online user operator = Meteor.users.findOne { operator: true, status: 'online' } unless operator throw new Meteor.Error 'no-operators', 'Sorry, no online operators' RocketChat.models.Rooms.insert _id: message.rid name: guest.username msgs: 1 lm: new Date() usernames: [ operator.username, guest.username ] t: 'd' ts: new Date() v: token: message.token RocketChat.models.Subscriptions.insert rid: message.rid name: guest.username alert: true open: true unread: 1 u: _id: operator._id username: operator.username t: 'd' room = Meteor.call 'canAccessRoom', message.rid, guest._id if not room throw new Meteor.Error 'cannot-acess-room' RocketChat.sendMessage guest, message, room
30894
Meteor.methods registerGuest: (token) -> check token, String user = Meteor.users.findOne { "profile.token": token }, { fields: { _id: 1 } } if user? throw new Meteor.Error 'token-already-exists', 'Token already exists' pass = <PASSWORD>() loop qt = Meteor.users.find({ 'profile.guest': true }).count() + 1 user = 'guest-' + qt userExists = Meteor.users.findOne { 'username': user }, { fields: { _id: 1 } } break if not userExists userData = username: user password: <PASSWORD> userId = Accounts.createUser userData Meteor.users.update userId, $set: name: user "profile.guest": true "profile.token": token return { user: user pass: <PASSWORD> } sendMessageLivechat: (message) -> console.log 'sendMessageLivechat ->',arguments check message.rid, String check message.token, String guest = Meteor.users.findOne Meteor.userId(), fields: username: 1 room = RocketChat.models.Rooms.findOneById message.rid if not room? # find an online user operator = Meteor.users.findOne { operator: true, status: 'online' } unless operator throw new Meteor.Error 'no-operators', 'Sorry, no online operators' RocketChat.models.Rooms.insert _id: message.rid name: guest.username msgs: 1 lm: new Date() usernames: [ operator.username, guest.username ] t: 'd' ts: new Date() v: token: message.token RocketChat.models.Subscriptions.insert rid: message.rid name: guest.username alert: true open: true unread: 1 u: _id: operator._id username: operator.username t: 'd' room = Meteor.call 'canAccessRoom', message.rid, guest._id if not room throw new Meteor.Error 'cannot-acess-room' RocketChat.sendMessage guest, message, room
true
Meteor.methods registerGuest: (token) -> check token, String user = Meteor.users.findOne { "profile.token": token }, { fields: { _id: 1 } } if user? throw new Meteor.Error 'token-already-exists', 'Token already exists' pass = PI:PASSWORD:<PASSWORD>END_PI() loop qt = Meteor.users.find({ 'profile.guest': true }).count() + 1 user = 'guest-' + qt userExists = Meteor.users.findOne { 'username': user }, { fields: { _id: 1 } } break if not userExists userData = username: user password: PI:PASSWORD:<PASSWORD>END_PI userId = Accounts.createUser userData Meteor.users.update userId, $set: name: user "profile.guest": true "profile.token": token return { user: user pass: PI:PASSWORD:<PASSWORD>END_PI } sendMessageLivechat: (message) -> console.log 'sendMessageLivechat ->',arguments check message.rid, String check message.token, String guest = Meteor.users.findOne Meteor.userId(), fields: username: 1 room = RocketChat.models.Rooms.findOneById message.rid if not room? # find an online user operator = Meteor.users.findOne { operator: true, status: 'online' } unless operator throw new Meteor.Error 'no-operators', 'Sorry, no online operators' RocketChat.models.Rooms.insert _id: message.rid name: guest.username msgs: 1 lm: new Date() usernames: [ operator.username, guest.username ] t: 'd' ts: new Date() v: token: message.token RocketChat.models.Subscriptions.insert rid: message.rid name: guest.username alert: true open: true unread: 1 u: _id: operator._id username: operator.username t: 'd' room = Meteor.call 'canAccessRoom', message.rid, guest._id if not room throw new Meteor.Error 'cannot-acess-room' RocketChat.sendMessage guest, message, room
[ { "context": "port\n username: 'a'\n password: 'b'\n\n @sut.getOpenEwsRequest {}, (@error) => ", "end": 829, "score": 0.9992998838424683, "start": 828, "tag": "PASSWORD", "value": "b" } ]
test/services/authenticated-request-spec.coffee
octoblu/bourse
0
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' shmock = require 'shmock' enableDestroy = require 'server-destroy' AuthenticatedRequest = require '../../src/services/authenticated-request' describe 'AuthenticatedRequest', -> beforeEach -> @responseDelay = 0 delayResponse = (req, res, next) => setTimeout next, @responseDelay @server = shmock null, [delayResponse] enableDestroy @server afterEach (done) -> @server.destroy done describe '->getOpenEwsRequest', -> describe 'when the request times out', -> beforeEach (done) -> @responseDelay = 10000 @sut = new AuthenticatedRequest timeout: 1 protocol: 'http' hostname: 'localhost' port: @server.address().port username: 'a' password: 'b' @sut.getOpenEwsRequest {}, (@error) => done() it 'should yield an error', -> expect(@error.message).to.contain 'TIMEDOUT'
17386
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' shmock = require 'shmock' enableDestroy = require 'server-destroy' AuthenticatedRequest = require '../../src/services/authenticated-request' describe 'AuthenticatedRequest', -> beforeEach -> @responseDelay = 0 delayResponse = (req, res, next) => setTimeout next, @responseDelay @server = shmock null, [delayResponse] enableDestroy @server afterEach (done) -> @server.destroy done describe '->getOpenEwsRequest', -> describe 'when the request times out', -> beforeEach (done) -> @responseDelay = 10000 @sut = new AuthenticatedRequest timeout: 1 protocol: 'http' hostname: 'localhost' port: @server.address().port username: 'a' password: '<PASSWORD>' @sut.getOpenEwsRequest {}, (@error) => done() it 'should yield an error', -> expect(@error.message).to.contain 'TIMEDOUT'
true
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' shmock = require 'shmock' enableDestroy = require 'server-destroy' AuthenticatedRequest = require '../../src/services/authenticated-request' describe 'AuthenticatedRequest', -> beforeEach -> @responseDelay = 0 delayResponse = (req, res, next) => setTimeout next, @responseDelay @server = shmock null, [delayResponse] enableDestroy @server afterEach (done) -> @server.destroy done describe '->getOpenEwsRequest', -> describe 'when the request times out', -> beforeEach (done) -> @responseDelay = 10000 @sut = new AuthenticatedRequest timeout: 1 protocol: 'http' hostname: 'localhost' port: @server.address().port username: 'a' password: 'PI:PASSWORD:<PASSWORD>END_PI' @sut.getOpenEwsRequest {}, (@error) => done() it 'should yield an error', -> expect(@error.message).to.contain 'TIMEDOUT'
[ { "context": "###\n X-Wing Squad Builder 2.0\n Stephen Kim <raithos@gmail.com>\n https://raithos.github.io", "end": 48, "score": 0.9996230006217957, "start": 37, "tag": "NAME", "value": "Stephen Kim" }, { "context": "###\n X-Wing Squad Builder 2.0\n Stephen Kim <raithos@gmail.com>\n https://raithos.github.io\n###\nexportObj = ex", "end": 67, "score": 0.999930739402771, "start": 50, "tag": "EMAIL", "value": "raithos@gmail.com" }, { "context": "Changed'\n\n newSquadFromScratch: (squad_name = 'New Squadron') ->\n @squad_name_input.val squad", "end": 6608, "score": 0.6136641502380371, "start": 6605, "tag": "NAME", "value": "New" }, { "context": " <input type=\"checkbox\" checked /> Is Dee Yun the worst?\n </label>\n <", "end": 42094, "score": 0.8937793374061584, "start": 42087, "tag": "NAME", "value": "Dee Yun" }, { "context": "esetCurrentSquad()\n @current_squad.name = 'Random Squad'\n @container.trigger 'xwing-backend:squadN", "end": 164962, "score": 0.7955842018127441, "start": 164950, "tag": "NAME", "value": "Random Squad" }, { "context": " for upgrade_name in exportObj.quickbuildsById[@quickbuildId].upgrades ? []\n upgrade_data = exp", "end": 196990, "score": 0.5477796196937561, "start": 196978, "tag": "USERNAME", "value": "quickbuildId" }, { "context": " quickbuild = exportObj.quickbuildsById[@quickbuildId]\n threat = if @primary then quickbuild", "end": 198132, "score": 0.9116895198822021, "start": 198119, "tag": "USERNAME", "value": "@quickbuildId" }, { "context": "uildId != -1 then exportObj.quickbuildsById[@quickbuildId].suffix else \"\"} (#{if @quickbuildId != -1 then (", "end": 202016, "score": 0.644884467124939, "start": 202009, "tag": "USERNAME", "value": "buildId" }, { "context": "(if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})\"\n ", "end": 202120, "score": 0.5127460956573486, "start": 202115, "tag": "USERNAME", "value": "build" } ]
coffeescripts/system/xwing.coffee
piffopi/xwing
0
### X-Wing Squad Builder 2.0 Stephen Kim <raithos@gmail.com> https://raithos.github.io ### exportObj = exports ? this exportObj.sortHelper = (a, b) -> if a.points == b.points a_name = a.text.replace(/[^a-z0-9]/ig, '') b_name = b.text.replace(/[^a-z0-9]/ig, '') if a_name == b_name 0 else if a_name > b_name then 1 else -1 else if typeof(a.points) == "string" # handling cases where points value is "*" instead of a number 1 else if a.points > b.points then 1 else -1 exportObj.toTTS = (txt) -> if not txt? null else txt.replace(/\(.*\)/g,"").replace("�",'"').replace("�",'"') exportObj.slotsMatching = (slota, slotb) -> return true if slota == slotb return false if slota != 'HardpointShip' and slotb != 'HardpointShip' return true if slota == 'Torpedo' or slota == 'Cannon' or slota == 'Missile' return true if slotb == 'Torpedo' or slotb == 'Cannon' or slotb == 'Missile' return false $.isMobile = -> if (navigator.userAgent.match /(iPhone|iPod|iPad|Android)/i) or navigator.maxTouchPoints > 1 return true return false $.randomInt = (n) -> Math.floor(Math.random() * n) $.isElementInView = (element, fullyInView) -> pageTop = $(window).scrollTop() pageBottom = pageTop + $(window).height() elementTop = $(element).offset().top elementBottom = elementTop + $(element).height() if fullyInView return ((pageTop < elementTop) && (pageBottom > elementBottom)) else return ((elementTop <= pageBottom) && (elementBottom >= pageTop)) # ripped from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values $.getParameterByName = (name) -> name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") regexS = "[\\?&]" + name + "=([^&#]*)" regex = new RegExp(regexS) results = regex.exec(window.location.search) if results == null return "" else return decodeURIComponent(results[1].replace(/\+/g, " ")) Array::intersects = (other) -> for item in this if item in other return true return false Array::removeItem = (item) -> idx = @indexOf item @splice(idx, 1) unless idx == -1 this String::capitalize = -> @charAt(0).toUpperCase() + @slice(1) String::getXWSBaseName = -> @split('-')[0] URL_BASE = "#{window.location.protocol}//#{window.location.host}#{window.location.pathname}" SQUAD_DISPLAY_NAME_MAX_LENGTH = 24 statAndEffectiveStat = (base_stat, effective_stats, key) -> if base_stat? """#{base_stat}#{if (effective_stats? and effective_stats[key]? and effective_stats[key] != base_stat) then " (#{effective_stats[key]})" else ""}""" else if effective_stats? and effective_stats[key]? """0 (#{effective_stats[key]})""" else "0" getPrimaryFaction = (faction) -> switch faction when 'Rebel Alliance' 'Rebel Alliance' when 'Galactic Empire' 'Galactic Empire' else faction conditionToHTML = (condition) -> html = $.trim """ <div class="condition"> <div class="name">#{if condition.unique then "&middot;&nbsp;" else ""}#{if condition.display_name then condition.display_name else condition.name}</div> <div class="text">#{condition.text}</div> </div> """ # Assumes cards.js will be loaded class exportObj.SquadBuilder constructor: (args) -> # args @container = $ args.container @faction = $.trim args.faction @printable_container = $ args.printable_container @tab = $ args.tab # internal state @ships = [] @uniques_in_use = Pilot: [] Upgrade: [] Slot: [] @standard_list = Upgrade: [] Ship: [] @suppress_automatic_new_ship = false @tooltip_currently_displaying = null @randomizer_options = sources: null points: 200 bid_goal: 5 ships_or_upgrades: 3 ship_limit: 0 collection_only: true fill_zero_pts: false @total_points = 0 # a squad given in the link is loaded on construction of that builder. It will set all gamemodes of already existing builders accordingly, but we did not exists back than. So we copy over the gamemode @isHyperspace = exportObj.builders[0]?.isHyperspace ? false @isEpic = exportObj.builders[0]?.isEpic ? false @isQuickbuild = exportObj.builders[0]?.isQuickbuild ? false @backend = null @current_squad = {} @language = 'English' @collection = null @current_obstacles = [] @setupUI() @game_type_selector.val (exportObj.builders[0] ? @).game_type_selector.val() @setupEventHandlers() window.setInterval @updatePermaLink, 250 @isUpdatingPoints = false if $.getParameterByName('f') == @faction @resetCurrentSquad(true) @loadFromSerialized $.getParameterByName('d') else @resetCurrentSquad() @addShip() resetCurrentSquad: (initial_load=false) -> default_squad_name = 'Unnamed Squadron' squad_name = $.trim(@squad_name_input.val()) or default_squad_name if initial_load and $.trim $.getParameterByName('sn') squad_name = $.trim $.getParameterByName('sn') squad_obstacles = [] if initial_load and $.trim $.getParameterByName('obs') squad_obstacles = ($.trim $.getParameterByName('obs')).split(",").slice(0, 3) @current_obstacles = squad_obstacles else if @current_obstacles squad_obstacles = @current_obstacles @current_squad = id: null name: squad_name dirty: false additional_data: points: @total_points description: '' cards: [] notes: '' obstacles: squad_obstacles tag: '' faction: @faction if @total_points > 0 if squad_name == default_squad_name @current_squad.name = 'Unsaved Squadron' @current_squad.dirty = true @container.trigger 'xwing-backend:squadNameChanged' @container.trigger 'xwing-backend:squadDirtinessChanged' newSquadFromScratch: (squad_name = 'New Squadron') -> @squad_name_input.val squad_name @removeAllShips() @addShip() if not @suppress_automatic_new_ship @current_obstacles = [] @resetCurrentSquad() @notes.val '' @tag.val '' setupUI: -> DEFAULT_RANDOMIZER_POINTS = 200 DEFAULT_RANDOMIZER_TIMEOUT_SEC = 4 DEFAULT_RANDOMIZER_BID_GOAL = 5 DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES = 3 DEFAULT_RANDOMIZER_SHIP_LIMIT = 0 @status_container = $ document.createElement 'DIV' @status_container.addClass 'container-fluid' @status_container.append $.trim ''' <div class="row squad-name-and-points-row"> <div class="col-md-3 squad-name-container"> <div class="display-name"> <span class="squad-name"></span> <i class="far fa-edit"></i> </div> <div class="input-append"> <input type="text" maxlength="64" placeholder="Name your squad..." /> <button class="btn save"><i class="fa fa-pen-square"></i></button> </div> <br /> <select class="game-type-selector"> <option value="standard">Extended</option> <option value="hyperspace">Hyperspace</option> <option value="epic">Epic</option> <option value="quickbuild">Quickbuild</option> </select> </div> <div class="col-md-4 points-display-container"> Points: <span class="total-points">0</span> / <input type="number" class="desired-points" value="200"> <span class="points-remaining-container">(<span class="points-remaining"></span>&nbsp;left) <span class="points-destroyed red"></span></span> <span class="content-warning unreleased-content-used d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning loading-failed-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning collection-invalid d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning ship-number-invalid-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated">A tournament legal squad must contain 2-8 ships!</span></span> <span class="content-warning multi-faction-warning-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated">Multi-Faction Lists are NEVER tournament legal!</span></span> </div> <div class="col-md-5 float-right button-container"> <div class="btn-group float-right"> <button class="btn btn-info view-as-text"><span class="d-none d-lg-block"><i class="fa fa-print"></i>&nbsp;Print/Export</span><span class="d-lg-none"><i class="fa fa-print"></i></span></button> <a class="btn btn-primary d-none collection"><span class="d-none d-lg-block"><i class="fa fa-folder-open"></i> Your Collection</span><span class="d-lg-none"><i class="fa fa-folder-open"></i></span></a> <!-- Randomize button is marked as danger, since it creates a new squad --> <button class="btn btn-danger randomize"><span class="d-none d-lg-block"><i class="fa fa-random"></i> Randomize!</span><span class="d-lg-none"><i class="fa fa-random"></i></span></button> <button class="btn btn-danger dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a class="dropdown-item randomize-options">Randomizer Options</a></li> <li><a class="dropdown-item misc-settings">Misc Settings</a></li> </ul> </div> </div> </div> <div class="row squad-save-buttons"> <div class="col-md-12"> <button class="show-authenticated btn btn-primary save-list"><i class="far fa-save"></i>&nbsp;Save</button> <button class="show-authenticated btn btn-primary save-list-as"><i class="far fa-file"></i>&nbsp;Save As...</button> <button class="show-authenticated btn btn-primary delete-list disabled"><i class="fa fa-trash"></i>&nbsp;Delete</button> <button class="show-authenticated btn btn-info backend-list-my-squads show-authenticated"><i class="fa fa-download"></i>&nbsp;Load Squad</button> <button class="btn btn-info import-squad"><i class="fa fa-file-import"></i>&nbsp;Import</button> <button class="btn btn-danger clear-squad"><i class="fa fa-plus-circle"></i>&nbsp;New Squad</button> <span class="show-authenticated backend-status"></span> </div> </div> ''' @container.append @status_container @xws_import_modal = $ document.createElement 'DIV' @xws_import_modal.addClass 'modal fade import-modal d-print-none' @xws_import_modal.tabindex = "-1" @xws_import_modal.role = "dialog" @xws_import_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>XWS Import</h3> <button type="button" class="close d-print-none" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> Import your list via XWS into YASB.<br> <i>XWS is a common format to share lists between applications.</i> <div class="container-fluid"> <textarea class="xws-content" placeholder="Paste XWS here"></textarea> </div> </div> <div class="modal-footer d-print-none"> <span class="xws-import-status"></span>&nbsp; <button class="btn btn-danger import-xws">Import</button> </div> </div> </div> """ @from_xws_button = @container.find('button.import-squad') @from_xws_button.click (e) => e.preventDefault() @xws_import_modal.find('.xws-import-status').text ' ' @xws_import_modal.modal 'show' @load_xws_button = $ @xws_import_modal.find('button.import-xws') @load_xws_button.click (e) => e.preventDefault() exportObj.loadXWSButton(@xws_import_modal) @container.append @xws_import_modal @list_modal = $ document.createElement 'DIV' @list_modal.addClass 'modal fade text-list-modal' @list_modal.tabindex = "-1" @list_modal.role = "dialog" @container.append @list_modal @list_modal.append $.trim """ <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <div class="d-print-none"> <h4 class="modal-title"><span class="squad-name"></span> (<span class="total-points"></span>)</h4> </div> <div class="d-none d-print-block"> <div class="fancy-header"> <div class="squad-name"></div> <div class="squad-faction"></div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle"> <span class="total-points"></span> </div> </div> </div> </div> <div class="fancy-under-header"></div> </div> <button type="button" class="close d-print-none" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <div class="fancy-list"></div> <div class="simple-list"></div> <div class="simplecopy-list"> <p>Copy the below and paste it elsewhere.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="reddit-list"> <p>Copy the below and paste it into your reddit post.</p> <p>Make sure that the post editor is set to markdown mode.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="tts-list"> <p>Copy the below and paste it into the Tabletop Simulator.</p> <textarea></textarea><br /><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="bbcode-list"> <p>Copy the BBCode below and paste it into your forum post.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="html-list"> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="xws-list"> <p>Copy and paste this into an XWS-compliant application. <div class="row full-row"> <div class="col d-inline-block d-none d-sm-block"><textarea></textarea><br /><button class="btn btn-modal btn-copy">Copy</button></div> <div class="col d-inline-block d-none d-sm-block qrcode-container" id="xws-qrcode-container"></div> </div> </div> </div> <div class="container-fluid modal-footer d-print-none"> <div class="row full-row"> <div class="col d-inline-block d-none d-sm-block right-col"> <label class="color-skip-text-checkbox"> Skip Card Text <input type="checkbox" class="toggle-skip-text-print" /> </label><br /> <label class="vertical-space-checkbox"> Add Space for Cards <input type="checkbox" class="toggle-vertical-space" /> </label><br /> <label class="maneuver-print-checkbox"> Include Maneuvers Chart <input type="checkbox" class="toggle-maneuver-print" /> </label><br /> <label class="expanded-shield-hull-print-checkbox"> Expand Shield and Hull <input type="checkbox" class="toggle-expanded-shield-hull-print" /> </label> </div> <div class="col d-inline-block d-none d-sm-block right-col"> <label class="color-print-checkbox"> Print Color <input type="checkbox" class="toggle-color-print" checked="checked" /> </label><br /> <label class="qrcode-checkbox"> Include QR codes <input type="checkbox" class="toggle-juggler-qrcode" checked="checked" /> </label><br /> <label class="obstacles-checkbox"> Include Obstacle Choices <input type="checkbox" class="toggle-obstacles" /> </label> </div> </div> <div class="row btn-group list-display-mode"> <button class="btn btn-modal select-simple-view">Simple</button> <button class="btn btn-modal select-fancy-view d-none d-sm-block">Fancy</button> <button class="btn btn-modal select-simplecopy-view">Text</button> <button class="btn btn-modal select-tts-view">TTS</button> <button class="btn btn-modal select-reddit-view">Reddit</button> <button class="btn btn-modal select-bbcode-view">BBCode</button> <button class="btn btn-modal select-html-view">HTML</button> <button class="btn btn-modal select-xws-view">XWS</button> </div> <button class="btn btn-modal print-list d-none d-sm-block"><i class="fa fa-print"></i>&nbsp;Print</button> </div> </div> </div> """ @fancy_container = $ @list_modal.find('.fancy-list') @fancy_total_points_container = $ @list_modal.find('div.modal-header .total-points') @simple_container = $ @list_modal.find('div.modal-body .simple-list') @reddit_container = $ @list_modal.find('div.modal-body .reddit-list') @reddit_textarea = $ @reddit_container.find('textarea') @reddit_textarea.attr 'readonly', 'readonly' @simplecopy_container = $ @list_modal.find('div.modal-body .simplecopy-list') @simplecopy_textarea = $ @simplecopy_container.find('textarea') @simplecopy_textarea.attr 'readonly', 'readonly' @tts_container = $ @list_modal.find('div.modal-body .tts-list') @tts_textarea = $ @tts_container.find('textarea') @tts_textarea.attr 'readonly', 'readonly' @xws_container = $ @list_modal.find('div.modal-body .xws-list') @xws_textarea = $ @xws_container.find('textarea') @xws_textarea.attr 'readonly', 'readonly' @bbcode_container = $ @list_modal.find('div.modal-body .bbcode-list') @bbcode_textarea = $ @bbcode_container.find('textarea') @bbcode_textarea.attr 'readonly', 'readonly' @htmlview_container = $ @list_modal.find('div.modal-body .html-list') @html_textarea = $ @htmlview_container.find('textarea') @html_textarea.attr 'readonly', 'readonly' @toggle_vertical_space_container = $ @list_modal.find('.vertical-space-checkbox') @toggle_color_print_container = $ @list_modal.find('.color-print-checkbox') @toggle_color_skip_text = $ @list_modal.find('.color-skip-text-checkbox') @toggle_maneuver_dial_container = $ @list_modal.find('.maneuver-print-checkbox') @toggle_expanded_shield_hull_container = $ @list_modal.find('.expanded-shield-hull-print-checkbox') @toggle_qrcode_container = $ @list_modal.find('.qrcode-checkbox') @toggle_obstacle_container = $ @list_modal.find('.obstacles-checkbox') @btn_print_list = ($ @list_modal.find('.print-list'))[0] @list_modal.on 'click', 'button.btn-copy', (e) => @self = $(e.currentTarget) @self.siblings('textarea').select() @success = document.execCommand('copy') if @success @self.addClass 'btn-success' setTimeout ( => @self.removeClass 'btn-success' ), 1000 @select_simple_view_button = $ @list_modal.find('.select-simple-view') @select_simple_view_button.click (e) => @select_simple_view_button.blur() unless @list_display_mode == 'simple' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_simple_view_button.addClass 'btn-inverse' @list_display_mode = 'simple' @simple_container.show() @fancy_container.hide() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @xws_container.hide() @bbcode_container.hide() @htmlview_container.hide() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.show() @toggle_obstacle_container.show() @btn_print_list.disabled = false; @select_fancy_view_button = $ @list_modal.find('.select-fancy-view') @select_fancy_view_button.click (e) => @select_fancy_view_button.blur() unless @list_display_mode == 'fancy' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_fancy_view_button.addClass 'btn-inverse' @list_display_mode = 'fancy' @fancy_container.show() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @bbcode_container.hide() @htmlview_container.hide() @xws_container.hide() @toggle_vertical_space_container.show() @toggle_color_print_container.show() @toggle_color_skip_text.show() @toggle_maneuver_dial_container.show() @toggle_expanded_shield_hull_container.show() @toggle_qrcode_container.show() @toggle_obstacle_container.show() @btn_print_list.disabled = false; @select_reddit_view_button = $ @list_modal.find('.select-reddit-view') @select_reddit_view_button.click (e) => @select_reddit_view_button.blur() unless @list_display_mode == 'reddit' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_reddit_view_button.addClass 'btn-inverse' @list_display_mode = 'reddit' @reddit_container.show() @simplecopy_container.hide() @bbcode_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @reddit_textarea.select() @reddit_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_simplecopy_view_button = $ @list_modal.find('.select-simplecopy-view') @select_simplecopy_view_button.click (e) => @select_simplecopy_view_button.blur() unless @list_display_mode == 'simplecopy' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_simplecopy_view_button.addClass 'btn-inverse' @list_display_mode = 'simplecopy' @reddit_container.hide() @simplecopy_container.show() @bbcode_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @simplecopy_textarea.select() @simplecopy_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_tts_view_button = $ @list_modal.find('.select-tts-view') @select_tts_view_button.click (e) => @select_tts_view_button.blur() unless @list_display_mode == 'tts' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_tts_view_button.addClass 'btn-inverse' @list_display_mode = 'tts' @tts_container.show() @bbcode_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @fancy_container.hide() @tts_textarea.select() @tts_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_bbcode_view_button = $ @list_modal.find('.select-bbcode-view') @select_bbcode_view_button.click (e) => @select_bbcode_view_button.blur() unless @list_display_mode == 'bbcode' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_bbcode_view_button.addClass 'btn-inverse' @list_display_mode = 'bbcode' @bbcode_container.show() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @bbcode_textarea.select() @bbcode_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_html_view_button = $ @list_modal.find('.select-html-view') @select_html_view_button.click (e) => @select_html_view_button.blur() unless @list_display_mode == 'html' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_html_view_button.addClass 'btn-inverse' @list_display_mode = 'html' @reddit_container.hide() @simplecopy_container.hide() @tts_container.hide() @bbcode_container.hide() @htmlview_container.show() @simple_container.hide() @fancy_container.hide() @xws_container.hide() @html_textarea.select() @html_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_xws_view_button = $ @list_modal.find('.select-xws-view') @select_xws_view_button.click (e) => @select_xws_view() if $(window).width() >= 768 @simple_container.hide() @select_fancy_view_button.click() else @select_simple_view_button.click() @clear_squad_button = $ @status_container.find('.clear-squad') @clear_squad_button.click (e) => if @current_squad.dirty and @backend? @backend.warnUnsaved this, () => @newSquadFromScratch() else @newSquadFromScratch() @squad_name_container = $ @status_container.find('div.squad-name-container') @squad_name_display = $ @container.find('.display-name') @squad_name_placeholder = $ @container.find('.squad-name') @squad_name_input = $ @squad_name_container.find('input') @squad_name_save_button = $ @squad_name_container.find('button.save') @squad_name_input.closest('div').hide() @points_container = $ @status_container.find('div.points-display-container') @total_points_span = $ @points_container.find('.total-points') @game_type_selector = $ @status_container.find('.game-type-selector') @game_type_selector.select2 minimumResultsForSearch: -1 @game_type_selector.change (e) => # $(window).trigger 'xwing:gameTypeChanged', @game_type_selector.val() @onGameTypeChanged @game_type_selector.val() @desired_points_input = $ @points_container.find('.desired-points') @desired_points_input.change (e) => @onPointsUpdated $.noop @points_remaining_span = $ @points_container.find('.points-remaining') @points_destroyed_span = $ @points_container.find('.points-destroyed') @points_remaining_container = $ @points_container.find('.points-remaining-container') @unreleased_content_used_container = $ @points_container.find('.unreleased-content-used') @loading_failed_container = $ @points_container.find('.loading-failed-container') @ship_number_invalid_container = $ @points_container.find('.ship-number-invalid-container') @multi_faction_warning_container = $ @points_container.find('.multi-faction-warning-container') @collection_invalid_container = $ @points_container.find('.collection-invalid') @view_list_button = $ @status_container.find('div.button-container button.view-as-text') @randomize_button = $ @status_container.find('div.button-container button.randomize') @customize_randomizer = $ @status_container.find('div.button-container a.randomize-options') @misc_settings = $ @status_container.find('div.button-container a.misc-settings') @backend_status = $ @status_container.find('.backend-status') @backend_status.hide() @collection_button = $ @status_container.find('div.button-container a.collection') @collection_button.click (e) => e.preventDefault() unless @collection_button.prop('disabled') @collection.modal.modal 'show' @squad_name_input.keypress (e) => if e.which == 13 @squad_name_save_button.click() false @squad_name_input.change (e) => @backend_status.fadeOut 'slow' @squad_name_input.blur (e) => @squad_name_input.change() @squad_name_save_button.click() @squad_name_display.click (e) => e.preventDefault() @squad_name_display.hide() @squad_name_input.val $.trim(@current_squad.name) # Because Firefox handles this badly window.setTimeout () => @squad_name_input.focus() @squad_name_input.select() , 100 @squad_name_input.closest('div').show() @squad_name_save_button.click (e) => e.preventDefault() @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' name = @current_squad.name = $.trim(@squad_name_input.val()) if name.length > 0 @squad_name_display.show() @container.trigger 'xwing-backend:squadNameChanged' @squad_name_input.closest('div').hide() @randomizer_options_modal = $ document.createElement('DIV') @randomizer_options_modal.addClass 'modal fade randomizer-modal' @randomizer_options_modal.tabindex = "-1" @randomizer_options_modal.role = "dialog" $('body').append @randomizer_options_modal @randomizer_options_modal.append $.trim """ <div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Random Squad Builder Options</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <form> <label> Maximal desired bid <input type="number" class="randomizer-bid-goal" value="#{DEFAULT_RANDOMIZER_BID_GOAL}" placeholder="#{DEFAULT_RANDOMIZER_BID_GOAL}" /> </label><br /> <label> Maximum Ship Count (0 for no limit) <input type="number" class="randomizer-ship-limit" value="#{DEFAULT_RANDOMIZER_SHIP_LIMIT}" placeholder="#{DEFAULT_RANDOMIZER_SHIP_LIMIT}" /> </label><br /> <label> More upgrades <input type="range" min="0" max="10" class="randomizer-ships-or-upgrades" value="#{DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES}" placeholder="#{DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES}" /> Less upgrades </label><br /> <label> <input type="checkbox" class="randomizer-collection-only" checked="checked"/> Only use items from collection </label><br /> <label> Sets and Expansions (default all) <select class="randomizer-sources" multiple="1" data-placeholder="Use all sets and expansions"> </select> </label><br /> <label> <input type="checkbox" class="randomizer-fill-zero-pts" /> Always fill 0-point slots </label><br /> <label> Maximum Seconds to Spend Randomizing <input type="number" class="randomizer-timeout" value="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" placeholder="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" /> </label> </form> </div> <div class="modal-footer"> <button class="btn btn-primary do-randomize" aria-hidden="true">Randomize!</button> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @randomizer_source_selector = $ @randomizer_options_modal.find('select.randomizer-sources') for expansion in exportObj.expansions opt = $ document.createElement('OPTION') opt.text expansion @randomizer_source_selector.append opt @randomizer_source_selector.select2 width: "100%" minimumResultsForSearch: if $.isMobile() then -1 else 0 @randomizer_collection_selector = ($ @randomizer_options_modal.find('.randomizer-collection-only'))[0] @randomizer_fill_zero_pts = ($ @randomizer_options_modal.find('.randomizer-fill-zero-pts'))[0] @randomize_button.click (e) => e.preventDefault() if @current_squad.dirty and @backend? @backend.warnUnsaved this, () => @randomize_button.click() else points = parseInt @desired_points_input.val() points = DEFAULT_RANDOMIZER_POINTS if (isNaN(points) or points <= 0) bid_goal = parseInt $(@randomizer_options_modal.find('.randomizer-bid-goal')).val() bid_goal = DEFAULT_RANDOMIZER_BID_GOAL if (isNaN(bid_goal) or bid_goal < 0) ship_limit = parseInt $(@randomizer_options_modal.find('.randomizer-ship-limit')).val() ship_limit = DEFAULT_RANDOMIZER_SHIP_LIMIT if (isNaN(ship_limit) or ship_limit < 0) ships_or_upgrades = parseInt $(@randomizer_options_modal.find('.randomizer-ships-or-upgrades')).val() ships_or_upgrades = DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES if (isNaN(ships_or_upgrades) or ships_or_upgrades < 0) timeout_sec = parseInt $(@randomizer_options_modal.find('.randomizer-timeout')).val() timeout_sec = DEFAULT_RANDOMIZER_TIMEOUT_SEC if (isNaN(timeout_sec) or timeout_sec <= 0) # console.log "points=#{points}, sources=#{@randomizer_source_selector.val()}, timeout=#{timeout_sec}" @randomSquad(points, @randomizer_source_selector.val(), timeout_sec * 1000, bid_goal, ship_limit, ships_or_upgrades, @randomizer_collection_selector.checked, @randomizer_fill_zero_pts.checked) @randomizer_options_modal.find('button.do-randomize').click (e) => e.preventDefault() @randomizer_options_modal.modal('hide') @randomize_button.click() @customize_randomizer.click (e) => e.preventDefault() @randomizer_options_modal.modal() @misc_settings_modal = $ document.createElement('DIV') @misc_settings_modal.addClass 'modal fade' @misc_settings_modal.tabindex = "-1" @misc_settings_modal.role = "dialog" $('body').append @misc_settings_modal @misc_settings_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Miscellaneous Settings</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <label class = "toggle-initiative-prefix-names misc-settings-label"> <input type="checkbox" class="initiative-prefix-names-checkbox misc-settings-checkbox" /> Put INI as prefix in front of names. </label><br /> <label> <input type="checkbox" checked /> Is Dee Yun the worst? </label> </div> <div class="modal-footer"> <span class="misc-settings-infoline"></span> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @misc_settings_infoline = $ @misc_settings_modal.find('.misc-settings-infoline') @misc_settings_initiative_prefix = $ @misc_settings_modal.find('.initiative-prefix-names-checkbox') if @backend? @backend.getSettings (st) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = st.showInitiativeInFrontOfPilotName? if st.showInitiativeInFrontOfPilotName? @misc_settings_initiative_prefix.prop('checked', true) else @waiting_for_backend ?= [] @waiting_for_backend.push => @backend.getSettings (st) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = st.showInitiativeInFrontOfPilotName? if st.showInitiativeInFrontOfPilotName? @misc_settings_initiative_prefix.prop('checked', true) @misc_settings_initiative_prefix.click (e) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = @misc_settings_initiative_prefix.prop('checked') if @backend? if @misc_settings_initiative_prefix.prop('checked') @backend.set 'showInitiativeInFrontOfPilotName', '1', (ds) => @misc_settings_infoline.text "Changes Saved" @misc_settings_infoline.fadeIn 100, => @misc_settings_infoline.fadeOut 3000 else @backend.deleteSetting 'showInitiativeInFrontOfPilotName', (dd) => @misc_settings_infoline.text "Changes Saved" @misc_settings_infoline.fadeIn 100, => @misc_settings_infoline.fadeOut 3000 @misc_settings.click (e) => e.preventDefault() @misc_settings_modal.modal() @misc_settings_initiative_prefix.prop('checked', exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix) @choose_obstacles_modal = $ document.createElement 'DIV' @choose_obstacles_modal.addClass 'modal fade choose-obstacles-modal' @choose_obstacles_modal.tabindex = "-1" @choose_obstacles_modal.role = "dialog" @container.append @choose_obstacles_modal @choose_obstacles_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <label class='choose-obstacles-description'>Choose up to three obstacles, to include in the permalink for use in external programs</label> </div> <div class="modal-body"> <div class="obstacle-select-container" style="float:left"> <select multiple class='obstacle-select' size="18"> <option class="coreasteroid0-select" value="coreasteroid0">Core Asteroid 0</option> <option class="coreasteroid1-select" value="coreasteroid1">Core Asteroid 1</option> <option class="coreasteroid2-select" value="coreasteroid2">Core Asteroid 2</option> <option class="coreasteroid3-select" value="coreasteroid3">Core Asteroid 3</option> <option class="coreasteroid4-select" value="coreasteroid4">Core Asteroid 4</option> <option class="coreasteroid5-select" value="coreasteroid5">Core Asteroid 5</option> <option class="yt2400debris0-select" value="yt2400debris0">YT2400 Debris 0</option> <option class="yt2400debris1-select" value="yt2400debris1">YT2400 Debris 1</option> <option class="yt2400debris2-select" value="yt2400debris2">YT2400 Debris 2</option> <option class="vt49decimatordebris0-select" value="vt49decimatordebris0">VT49 Debris 0</option> <option class="vt49decimatordebris1-select" value="vt49decimatordebris1">VT49 Debris 1</option> <option class="vt49decimatordebris2-select" value="vt49decimatordebris2">VT49 Debris 2</option> <option class="core2asteroid0-select" value="core2asteroid0">Force Awakens Asteroid 0</option> <option class="core2asteroid1-select" value="core2asteroid1">Force Awakens Asteroid 1</option> <option class="core2asteroid2-select" value="core2asteroid2">Force Awakens Asteroid 2</option> <option class="core2asteroid3-select" value="core2asteroid3">Force Awakens Asteroid 3</option> <option class="core2asteroid4-select" value="core2asteroid4">Force Awakens Asteroid 4</option> <option class="core2asteroid5-select" value="core2asteroid5">Force Awakens Asteroid 5</option> <option class="gascloud1-select" value="gascloud1">Gas Cloud 1</option> <option class="gascloud2-select" value="gascloud2">Gas Cloud 2</option> <option class="gascloud3-select" value="gascloud3">Gas Cloud 3</option> <option class="gascloud4-select" value="gascloud4">Gas Cloud 4</option> <option class="gascloud5-select" value="gascloud5">Gas Cloud 5</option> <option class="gascloud6-select" value="gascloud6">Gas Cloud 6</option> </select> </div> <div class="obstacle-image-container" style="display:none;"> <img class="obstacle-image" src="images/core2asteroid0.png" /> </div> </div> <div class="modal-footer d-print-none"> <button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @obstacles_select = @choose_obstacles_modal.find('.obstacle-select') @obstacles_select_image = @choose_obstacles_modal.find('.obstacle-image-container') # Backend @backend_list_squads_button = $ @container.find('button.backend-list-my-squads') @backend_list_squads_button.click (e) => e.preventDefault() if @backend? @backend.list this @backend_save_list_button = $ @container.find('button.save-list') @backend_save_list_button.click (e) => e.preventDefault() if @backend? and not @backend_save_list_button.hasClass('disabled') additional_data = points: @total_points description: @describeSquad() cards: @listCards() notes: @notes.val().substr(0, 1024) obstacles: @getObstacles() tag: @tag.val().substr(0, 1024) @backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;Saving squad... """ @backend_status.show() @backend_save_list_button.addClass 'disabled' await @backend.save @serialize(), @current_squad.id, @current_squad.name, @faction, additional_data, defer(results) if results.success @current_squad.dirty = false if @current_squad.id? @backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;Squad updated successfully. """ else @backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;New squad saved successfully. """ @current_squad.id = results.id @container.trigger 'xwing-backend:squadDirtinessChanged' else @backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ @backend_save_list_button.removeClass 'disabled' @backend_save_list_as_button = $ @container.find('button.save-list-as') @backend_save_list_as_button.addClass 'disabled' @backend_save_list_as_button.click (e) => e.preventDefault() if @backend? and not @backend_save_list_as_button.hasClass('disabled') @backend.showSaveAsModal this @backend_delete_list_button = $ @container.find('button.delete-list') @backend_delete_list_button.click (e) => e.preventDefault() if @backend? and not @backend_delete_list_button.hasClass('disabled') @backend.showDeleteModal this content_container = $ document.createElement 'DIV' content_container.addClass 'container-fluid' @container.append content_container content_container.append $.trim """ <div class="row"> <div class="col-md-9 ship-container"> <label class="notes-container show-authenticated col-md-10"> <span class="notes-name">Squad Notes:</span> <br /> <textarea class="squad-notes"></textarea> <br /> <span class="tag-name">Tag:</span> <input type="search" class="squad-tag"></input> </label> <div class="obstacles-container"> <button class="btn btn-info choose-obstacles"><i class="fa fa-cloud"></i>&nbsp;Choose Obstacles</button> </div> </div> <div class="col-md-3 info-container" id="info-container"> </div> </div> """ @ship_container = $ content_container.find('div.ship-container') @info_container = $ content_container.find('div.info-container') @obstacles_container = content_container.find('.obstacles-container') @notes_container = $ content_container.find('.notes-container') @notes = $ @notes_container.find('textarea.squad-notes') @tag = $ @notes_container.find('input.squad-tag') @info_container.append $.trim @createInfoContainerUI() @info_container.hide() @print_list_button = $ @container.find('button.print-list') @container.find('[rel=tooltip]').tooltip() # obstacles @obstacles_button = $ @container.find('button.choose-obstacles') @obstacles_button.click (e) => e.preventDefault() @showChooseObstaclesModal() # conditions @condition_container = $ document.createElement('div') @condition_container.addClass 'conditions-container d-flex flex-wrap' @container.append @condition_container @mobile_tooltip_modal = $ document.createElement 'DIV' @mobile_tooltip_modal.addClass 'modal fade choose-obstacles-modal d-print-none' @mobile_tooltip_modal.tabindex = "-1" @mobile_tooltip_modal.role = "dialog" @container.append @mobile_tooltip_modal @mobile_tooltip_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> </div> <div class="modal-body"> """ + @createInfoContainerUI() + """ </div> <div class="modal-footer"> <button class="btn btn-danger close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ createInfoContainerUI: -> return """ <div class="card info-well"> <div class="info-name"></div> <div class="info-type"></div> <span class="info-collection"></span> <table class="table-sm"> <tbody> <tr class="info-ship"> <td class="info-header">Ship</td> <td class="info-data"></td> </tr> <tr class="info-base"> <td class="info-header">Base</td> <td class="info-data"></td> </tr> <tr class="info-skill"> <td class="info-header">Initiative</td> <td class="info-data info-skill"></td> </tr> <tr class="info-engagement"> <td class="info-header">Engagement</td> <td class="info-data info-engagement"></td> </tr> <tr class="info-attack-bullseye"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-fullfront"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-left"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-leftarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-right"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-rightarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-back"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-turret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-doubleturret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-agility"> <td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td> <td class="info-data info-agility"></td> </tr> <tr class="info-hull"> <td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td> <td class="info-data info-hull"></td> </tr> <tr class="info-shields"> <td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td> <td class="info-data info-shields"></td> </tr> <tr class="info-force"> <td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td> <td class="info-data info-force"></td> </tr> <tr class="info-charge"> <td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td> <td class="info-data info-charge"></td> </tr> <tr class="info-energy"> <td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td> <td class="info-data info-energy"></td> </tr> <tr class="info-range"> <td class="info-header">Range</td> <td class="info-data info-range"></td><td class="info-rangebonus"><i class="xwing-miniatures-font red header-range xwing-miniatures-font-rangebonusindicator"></i></td> </tr> <tr class="info-actions"> <td class="info-header">Actions</td> <td class="info-data"></td> </tr> <tr class="info-upgrades"> <td class="info-header">Upgrades</td> <td class="info-data"></td> </tr> </tbody> </table> <p class="info-restrictions"></p> <p class="info-text"></p> <p class="info-maneuvers"></p> <br /> <span class="info-header info-sources">Sources:</span> <span class="info-data info-sources"></span> </div> """ setupEventHandlers: -> @container.on 'xwing:claimUnique', (e, unique, type, cb) => @claimUnique unique, type, cb .on 'xwing:releaseUnique', (e, unique, type, cb) => @releaseUnique unique, type, cb .on 'xwing:pointsUpdated', (e, cb=$.noop) => if @isUpdatingPoints cb() else @isUpdatingPoints = true @onPointsUpdated () => @isUpdatingPoints = false cb() .on 'xwing-backend:squadLoadRequested', (e, squad, cb=$.noop) => @onSquadLoadRequested squad cb() .on 'xwing-backend:squadDirtinessChanged', (e) => @onSquadDirtinessChanged() .on 'xwing-backend:squadNameChanged', (e) => @onSquadNameChanged() .on 'xwing:beforeLanguageLoad', (e, cb=$.noop) => @pretranslation_serialized = @serialize() cb() .on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) => if @language != language @language = language old_dirty = @current_squad.dirty if @pretranslation_serialized.length? @loadFromSerialized @pretranslation_serialized for ship in @ships ship.updateSelections() @current_squad.dirty = old_dirty @pretranslation_serialized = undefined cb() # Recently moved this here. Did this ever work? .on 'xwing:shipUpdated', (e, cb=$.noop) => all_allocated = true for ship in @ships ship.updateSelections() if ship.ship_selector.val() == '' all_allocated = false #console.log "all_allocated is #{all_allocated}, suppress_automatic_new_ship is #{@suppress_automatic_new_ship}" #console.log "should we add ship: #{all_allocated and not @suppress_automatic_new_ship}" @addShip() if all_allocated and not @suppress_automatic_new_ship $(window).on 'xwing-backend:authenticationChanged', (e) => @resetCurrentSquad() .on 'xwing-collection:created', (e, collection) => # console.log "#{@faction}: collection was created" @collection = collection # console.log "#{@faction}: Collection created, checking squad" @collection.onLanguageChange null, @language @checkCollection() @collection_button.removeClass 'd-none' .on 'xwing-collection:changed', (e, collection) => # console.log "#{@faction}: Collection changed, checking squad" @checkCollection() .on 'xwing-collection:destroyed', (e, collection) => @collection = null @collection_button.addClass 'd-none' .on 'xwing:pingActiveBuilder', (e, cb) => cb(this) if @container.is(':visible') .on 'xwing:activateBuilder', (e, faction, cb) => if faction == @faction @tab.tab('show') cb this .on 'xwing:gameTypeChanged', (e, gameType, cb=$.noop) => @onGameTypeChanged gameType, cb if @game_type_selector.val() != gameType @game_type_selector.val(gameType).trigger('change') @obstacles_select.change (e) => if @obstacles_select.val().length > 3 @obstacles_select.val(@current_squad.additional_data.obstacles) else previous_obstacles = @current_squad.additional_data.obstacles @current_obstacles = (o for o in @obstacles_select.val()) if (previous_obstacles?) new_selection = @current_obstacles.filter((element) => return previous_obstacles.indexOf(element) == -1) else new_selection = @current_obstacles if new_selection.length > 0 @showChooseObstaclesSelectImage(new_selection[0]) @current_squad.additional_data.obstacles = @current_obstacles @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' @container.trigger 'xwing:pointsUpdated' @view_list_button.click (e) => e.preventDefault() @showTextListModal() @print_list_button.click (e) => e.preventDefault() # Copy text list to printable @printable_container.find('.printable-header').html @list_modal.find('.modal-header').html() @printable_container.find('.printable-body').text '' switch @list_display_mode when 'simple' @printable_container.find('.printable-body').html @simple_container.html() else for ship in @ships @printable_container.find('.printable-body').append ship.toHTML() if ship.pilot? @printable_container.find('.fancy-ship').toggleClass 'tall', @list_modal.find('.toggle-vertical-space').prop('checked') @printable_container.find('.printable-body').toggleClass 'bw', not @list_modal.find('.toggle-color-print').prop('checked') if @list_modal.find('.toggle-skip-text-print').prop('checked') for text in @printable_container.find('.upgrade-text, .fancy-pilot-text') text.hidden = true if @list_modal.find('.toggle-maneuver-print').prop('checked') @printable_container.find('.printable-body').append @getSquadDialsAsHTML() expanded_hull_and_shield = @list_modal.find('.toggle-expanded-shield-hull-print').prop('checked') for container in @printable_container.find('.expanded-hull-or-shield') container.hidden = not expanded_hull_and_shield for container in @printable_container.find('.simple-hull-or-shield') container.hidden = expanded_hull_and_shield faction = switch @faction when 'Rebel Alliance' 'rebel' when 'Galactic Empire' 'empire' when 'Scum and Villainy' 'scum' when 'Resistance' 'rebel-outline' when 'First Order' 'firstorder' when 'Galactic Republic' 'republic' when 'Separatist Alliance' 'separatists' when 'All' 'first-player-4' @printable_container.find('.squad-faction').html """<i class="xwing-miniatures-font xwing-miniatures-font-#{faction}"></i>""" # List type if @isHyperspace @printable_container.find('.squad-name').append """ <i class="xwing-miniatures-font xwing-miniatures-font-first-player-1"></i>""" if @isEpic @printable_container.find('.squad-name').append """ <i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>""" # Notes, if present @printable_container.find('.printable-body').append $.trim """ <div class="version">Points Version: 1.9.0 March 2021</div> """ if $.trim(@notes.val()) != '' @printable_container.find('.printable-body').append $.trim """ <h5 class="print-notes">Notes:</h5> <pre class="print-notes"></pre> """ @printable_container.find('.printable-body pre.print-notes').text @notes.val() else # Conditions @printable_container.find('.printable-body').append $.trim """ <div class="print-conditions"></div> """ @printable_container.find('.printable-body .print-conditions').html @condition_container.html() # Obstacles if @list_modal.find('.toggle-obstacles').prop('checked') @printable_container.find('.printable-body').append $.trim """ <div class="obstacles"> <div>Mark the three obstacles you are using.</div> <img class="obstacle-silhouettes" src="images/xws-obstacles.png" /> </div> """ # Add List Juggler QR code query = @getPermaLinkParams(['sn', 'obs']) if query? and @list_modal.find('.toggle-juggler-qrcode').prop('checked') @printable_container.find('.printable-body').append $.trim """ <div class="qrcode-container"> <div class="permalink-container"> <div class="qrcode"></div> <div class="qrcode-text">Scan to open this list in the builder</div> </div> <div class="juggler-container"> <div class="qrcode"></div> <div class="qrcode-text">For List Juggler (When it's updated for 2.0)</div> </div> </div> """ text = "https://yasb-xws.herokuapp.com/juggler#{query}" @printable_container.find('.juggler-container .qrcode').qrcode render: 'div' ec: 'M' size: if text.length < 144 then 144 else 160 text: text text = "https://raithos.github.io/#{query}" @printable_container.find('.permalink-container .qrcode').qrcode render: 'div' ec: 'M' size: if text.length < 144 then 144 else 160 text: text window.print() $(window).resize => @select_simple_view_button.click() if $(window).width() < 768 and @list_display_mode != 'simple' for ship in @ships ship.checkPilotSelectorQueryModal() @notes.change @onNotesUpdated @tag.change @onNotesUpdated @notes.on 'keyup', @onNotesUpdated @tag.on 'keyup', @onNotesUpdated getPermaLinkParams: (ignored_params=[]) => params = {} params.f = encodeURI(@faction) unless 'f' in ignored_params params.d = encodeURI(@serialize()) unless 'd' in ignored_params params.sn = encodeURIComponent(@current_squad.name) unless 'sn' in ignored_params params.obs = encodeURI(@current_squad.additional_data.obstacles || '') unless 'obs' in ignored_params return "?" + ("#{k}=#{v}" for k, v of params).join("&") getPermaLink: (params=@getPermaLinkParams()) => "#{URL_BASE}#{params}" updatePermaLink: () => return unless @container.is(':visible') # gross but couldn't make clearInterval work next_params = @getPermaLinkParams() if window.location.search != next_params window.history.replaceState(next_params, '', @getPermaLink(next_params)) onNotesUpdated: => if @total_points > 0 @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' onGameTypeChanged: (gametype, cb=$.noop) => oldHyperspace = @isHyperspace oldEpic = @isEpic oldQuickbuild = @isQuickbuild @isHyperspace = false @isEpic = false @isQuickbuild = false switch gametype when 'standard' @desired_points_input.val 200 when 'hyperspace' @isHyperspace = true @desired_points_input.val 200 when 'epic' @isEpic = true @desired_points_input.val 500 when 'quickbuild' @isQuickbuild = true @desired_points_input.val 8 if oldQuickbuild != @isQuickbuild old_id = @current_squad.id @newSquadFromScratch($.trim(@current_squad.name)) @current_squad.id = old_id # we want to keep the ID, so we allow people to use the save button else old_id = @current_squad.id @container.trigger 'xwing:pointsUpdated', $.noop @container.trigger 'xwing:shipUpdated' cb() addStandardizedToList: (ship) -> if ship.data?.name? idx = @standard_list['Ship'].indexOf ship.data.name if idx > -1 for ship_upgrade in ship.upgrades if ship_upgrade.slot == @standard_list['Upgrade'][idx].slot ship_upgrade.setData @standard_list['Upgrade'][idx] break onPointsUpdated: (cb=$.noop) => tot_points = 0 points_dest = 0 unreleased_content_used = false # validating may remove the ship, if not only some upgrade, but the pilot himself is not valid. Thus iterate backwards over the array, so that is probably fine? for i in [@ships.length - 1 ... -1] ship = @ships[i] ship.validate() continue unless ship # if the ship has been removed, we no longer care about it # Standardized Loop, will integrate later for efficiency @addStandardizedToList(ship) tot_points += ship.getPoints() if ship.destroystate == 1 points_dest += Math.ceil ship.getPoints() / 2 else if ship.destroystate == 2 points_dest += ship.getPoints() ship_uses_unreleased_content = ship.checkUnreleasedContent() unreleased_content_used = ship_uses_unreleased_content if ship_uses_unreleased_content @total_points = tot_points @points_destroyed = points_dest @total_points_span.text @total_points points_left = parseInt(@desired_points_input.val()) - @total_points points_destroyed = parseInt(@total_points) @points_remaining_span.text points_left @points_destroyed_span.html if points_dest != 0 then """<i class="xwing-miniatures-font xwing-miniatures-font-hit"></i>#{points_dest}""" else "" @points_remaining_container.toggleClass 'red', (points_left < 0) @unreleased_content_used_container.toggleClass 'd-none', not unreleased_content_used @fancy_total_points_container.text @total_points # update text list @fancy_container.text '' @simple_container.html '<table class="simple-table"></table>' simplecopy_ships = [] reddit_ships = [] tts_ships = [] bbcode_ships = [] htmlview_ships = [] for ship in @ships if ship.pilot? @fancy_container.append ship.toHTML() #for dial in @fancy_container.find('.fancy-dial') #dial.hidden = true @simple_container.find('table').append ship.toTableRow() simplecopy_ships.push ship.toSimpleCopy() reddit_ships.push ship.toRedditText() tts_ships.push ship.toTTSText() bbcode_ships.push ship.toBBCode() htmlview_ships.push ship.toSimpleHTML() @htmlview_container.find('textarea').val $.trim """#{htmlview_ships.join '<br />'} <br /> <b><i>Total: #{@total_points}</i></b> <br /> <a href="#{@getPermaLink()}">View in Yet Another Squad Builder 2.0</a> """ @reddit_container.find('textarea').val $.trim """#{reddit_ships.join " \n"} \n**Total:** *#{@total_points}* \n \n[View in Yet Another Squad Builder 2.0](#{@getPermaLink()})""" @simplecopy_container.find('textarea').val $.trim """#{simplecopy_ships.join ""} \nTotal: #{@total_points} \n \nView in Yet Another Squad Builder 2.0: #{@getPermaLink()}""" #Additional code to add obstacles to TTS obstacles = @getObstacles() if (obstacles? and obstacles.length > 0) and (tts_ships.length > 0) tts_ships[tts_ships.length - 1] = tts_ships[tts_ships.length - 1].slice(0, -2) tts_obstacles = ' |' for obstacle in obstacles if obstacle? tts_obstacles += """ #{obstacle} /""" tts_obstacles = tts_obstacles.slice(0, -1) tts_ships.push tts_obstacles @tts_textarea.val $.trim """#{tts_ships.join ""}""" @bbcode_container.find('textarea').val $.trim """#{bbcode_ships.join "\n\n"}\n[b][i]Total: #{@total_points}[/i][/b]\n\n[url=#{@getPermaLink()}]View in Yet Another Squad Builder 2.0[/url]""" # console.log "#{@faction}: Squad updated, checking collection" @checkCollection() # update conditions used # this old version of phantomjs i'm using doesn't support Set if Set? conditions_set = new Set() for ship in @ships # shouldn't there be a set union ship.getConditions().forEach (condition) -> conditions_set.add(condition) conditions = [] conditions_set.forEach (condition) -> conditions.push(condition) conditions.sort (a, b) -> if a.name.canonicalize() < b.name.canonicalize() -1 else if b.name.canonicalize() > a.name.canonicalize() 1 else 0 @condition_container.text '' conditions.forEach (condition) => @condition_container.append conditionToHTML(condition) cb @total_points onSquadLoadRequested: (squad) => # console.log(squad.additional_data.obstacles) @current_squad = squad @backend_delete_list_button.removeClass 'disabled' @squad_name_input.val @current_squad.name @squad_name_placeholder.text @current_squad.name @current_obstacles = @current_squad.additional_data.obstacles @updateObstacleSelect(@current_squad.additional_data.obstacles) if squad.serialized.length? @loadFromSerialized squad.serialized @notes.val(squad.additional_data.notes ? '') @tag.val(squad.additional_data.tag ? '') @backend_status.fadeOut 'slow' @current_squad.dirty = false @container.trigger 'xwing-backend:squadDirtinessChanged' @container.trigger 'xwing-backend:squadNameChanged' onSquadDirtinessChanged: () => @current_squad.name = $.trim(@squad_name_input.val()) @backend_save_list_button.toggleClass 'disabled', not (@current_squad.dirty and @total_points > 0) @backend_save_list_as_button.toggleClass 'disabled', @total_points == 0 @backend_delete_list_button.toggleClass 'disabled', not @current_squad.id? if @ships.length > 1 $('meta[property="og:description"]').attr("content", "X-Wing Squadron by YASB 2.0: " + @current_squad.name + ": " + @describeSquad()) else $('meta[property="og:description"]').attr("content", "YASB 2.0 is a simple, fast, and easy to use squad builder for X-Wing Miniatures by Fantasy Flight Games.") # Moved XWS update to whenever the dirtyness changed rather than on points updated. @xws_textarea.val $.trim JSON.stringify(@toXWS()) $('#xws-qrcode-container').text '' $('#xws-qrcode-container').qrcode render: 'canvas' text: JSON.stringify(@toMinimalXWS()) ec: 'L' size: 128 onSquadNameChanged: () => if @current_squad.name.length > SQUAD_DISPLAY_NAME_MAX_LENGTH short_name = "#{@current_squad.name.substr(0, SQUAD_DISPLAY_NAME_MAX_LENGTH)}&hellip;" else short_name = @current_squad.name @squad_name_placeholder.text '' @squad_name_placeholder.append short_name @squad_name_input.val @current_squad.name return unless $.getParameterByName('f') == @faction if @current_squad.name != "Unnamed Squadron" and @current_squad.name != "Unsaved Squadron" if (document.title != "YASB 2.0 - " + @current_squad.name) document.title = "YASB 2.0 - " + @current_squad.name else document.title = "YASB 2.0" removeAllShips: -> while @ships.length > 0 @removeShip @ships[0] throw new Error("Ships not emptied") if @ships.length > 0 showTextListModal: -> # Display print/text view modal @list_modal.modal 'show' showXWSModal: (xws) -> # Display xws view modal @select_xws_view() @showTextListModal() showChooseObstaclesModal: -> @obstacles_select.val(@current_squad.additional_data.obstacles) @choose_obstacles_modal.modal 'show' showChooseObstaclesSelectImage: (obstacle) -> @image_name = 'images/' + obstacle + '.png' @obstacles_select_image.find('.obstacle-image').attr 'src', @image_name @obstacles_select_image.show() updateObstacleSelect: (obstacles) -> @current_obstacles = obstacles @obstacles_select.val(obstacles) serialize: -> serialization_version = 8 game_type_abbrev = switch @game_type_selector.val() when 'standard' 's' when 'hyperspace' 'h' when 'epic' 'e' when 'quickbuild' 'q' selected_points = $.trim @desired_points_input.val() """v#{serialization_version}Z#{game_type_abbrev}Z#{selected_points}Z#{( ship.toSerialized() for ship in @ships when ship.pilot? and (not @isQuickbuild or ship.primary) ).join 'Y'}""" changeGameTypeOnSquadLoad: (gametype) -> if @game_type_selector.val() != gametype $(window).trigger 'xwing:gameTypeChanged', gametype loadFromSerialized: (serialized) -> @suppress_automatic_new_ship = true # Clear all existing ships @removeAllShips() re = if "Z" in serialized then /^v(\d+)Z(.*)/ else /^v(\d+)!(.*)/ matches = re.exec serialized if matches? # versioned version = parseInt matches[1] # version 1-3 are 1st edition only (may be removed here) # version 4 is the final version of 1st edition x-wing, and has been the first few weeks of YASB 2.0 # version 5 is the first version for 2nd edtition x-wing only, it features extended (=standard), hyperspace, quickbuild and custom mode # version 6 has the only difference to version 5 is, that custom (=extended with != 200 points) has been removed and points are specified for all modes. # version 7 has arbitrary ordering of upgrades additionally supported # version 8 is the current version, replacing "!" with "Z" in the serialzed string, and 'Y' etc ship_splitter = if version > 7 then 'Y' else ';' # parse out game type [ game_type_abbrev, desired_points, serialized_ships ] = if version > 7 [g, p, s] = matches[2].split('Z') [g, parseInt(p), s] else [ game_type_and_point_abbrev, s ] = matches[2].split('!') if parseInt(game_type_and_point_abbrev.split('=')[1]) p = parseInt(game_type_and_point_abbrev.split('=')[1]) else p = 200 g = game_type_and_point_abbrev.split('=')[0] [ g, p, s ] # check if there are serialized ships to load if !serialized_ships? # something went wrong, we can't load that serialization @loading_failed_container.toggleClass 'd-none', false return switch game_type_abbrev when 's' @changeGameTypeOnSquadLoad 'standard' when 'h' @changeGameTypeOnSquadLoad 'hyperspace' when 'e' @changeGameTypeOnSquadLoad 'epic' when 'q' @changeGameTypeOnSquadLoad 'quickbuild' @desired_points_input.val desired_points @desired_points_input.change() ships_with_unmet_dependencies = [] if serialized_ships.length? for serialized_ship in serialized_ships.split(ship_splitter) unless serialized_ship == '' new_ship = @addShip() # try to create ship. fromSerialized returns false, if some upgrade have been skipped as they are not legal until now (e.g. 0-0-0 but vader is not yet in the squad) # if not the entire ship is valid, we'll try again later - but keep the valid part added, so other ships may already see some upgrades if (not new_ship.fromSerialized version, serialized_ship) or not new_ship.pilot # also check, if the pilot has been set (the pilot himself was not invalid) ships_with_unmet_dependencies.push [new_ship, serialized_ship] for ship in ships_with_unmet_dependencies # 2nd attempt to load ships with unmet dependencies. if not ship[0].pilot # create ship, if the ship was so invalid, that it in fact decided to not exist ship[0] = @addShip() ship[0].fromSerialized version, ship[1] @suppress_automatic_new_ship = false # Finally, the unassigned ship @addShip() select_xws_view: () -> @select_xws_view_button.blur() unless @list_display_mode == 'xws' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_xws_view_button.addClass 'btn-inverse' @list_display_mode = 'xws' @xws_container.show() @bbcode_container.hide() @htmlview_container.hide() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @fancy_container.hide() @tts_container.hide() @xws_textarea.select() @xws_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; uniqueIndex: (unique, type) -> if type not of @uniques_in_use throw new Error("Invalid unique type '#{type}'") @uniques_in_use[type].indexOf unique claimUnique: (unique, type, cb) => if @uniqueIndex(unique, type) < 0 # Claim pilots with the same canonical name for other in (exportObj.pilotsByUniqueName[unique.canonical_name.getXWSBaseName()] or []) if unique != other if @uniqueIndex(other, 'Pilot') < 0 # console.log "Also claiming unique pilot #{other.canonical_name} in use" @uniques_in_use['Pilot'].push other else throw new Error("Unique #{type} '#{unique.name}' already claimed as pilot") # Claim other upgrades with the same canonical name for otherslot, bycanonical of exportObj.upgradesBySlotUniqueName for canonical, other of bycanonical if canonical.getXWSBaseName() == unique.canonical_name.getXWSBaseName() and unique != other if @uniqueIndex(other, 'Upgrade') < 0 # console.log "Also claiming unique #{other.canonical_name} (#{otherslot}) in use" @uniques_in_use['Upgrade'].push other # else # throw new Error("Unique #{type} '#{unique.name}' already claimed as #{otherslot}") # Solitary Check if unique.solitary? @uniques_in_use['Slot'].push unique.slot @uniques_in_use[type].push unique else throw new Error("Unique #{type} '#{unique.name}' already claimed") cb() releaseUnique: (unique, type, cb) => idx = @uniqueIndex(unique, type) if idx >= 0 # Release all uniques with the same canonical name and base name for type, uniques of @uniques_in_use # Removing stuff in a loop sucks, so we'll construct a new list if type == 'Slot' if unique.solitary? @uniques_in_use[type] = [] for u in uniques if u != unique.slot # Keep this one @uniques_in_use[type].push u.slot else @uniques_in_use[type] = [] for u in uniques if u.canonical_name.getXWSBaseName() != unique.canonical_name.getXWSBaseName() # Keep this one @uniques_in_use[type].push u # else # console.log "Releasing #{u.name} (#{type}) with canonical name #{unique.canonical_name}" else throw new Error("Unique #{type} '#{unique.name}' not in use") cb() addShip: -> new_ship = new Ship builder: this container: @ship_container @ships.push new_ship @ship_number_invalid_container.toggleClass 'd-none', (@ships.length < 10 and @ships.length > 2) # bounds are 2..10 as we always have a "empty" ship at the bottom @multi_faction_warning_container.toggleClass 'd-none', (@faction != "All") new_ship removeShip: (ship, cb=$.noop) -> if ship?.destroy? await ship.destroy defer() await @container.trigger 'xwing:pointsUpdated', defer() @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' @ship_number_invalid_container.toggleClass 'd-none', (@ships.length < 10 and @ships.length > 2) @multi_faction_warning_container.toggleClass 'd-none', (@faction != "All") cb() matcher: (item, term) -> item.toUpperCase().indexOf(term.toUpperCase()) >= 0 isOurFaction: (faction, alt_faction = '') -> check_faction = @faction if @faction == "All" if alt_faction != '' check_faction = alt_faction else return true if faction instanceof Array for f in faction if getPrimaryFaction(f) == check_faction return true false else getPrimaryFaction(faction) == check_faction isItemAvailable: (item_data, shipCheck=false) -> # this method is not even invoked by most quickbuild stuff to check availability for quickbuild squads, as the method was formerly just telling apart extended/hyperspace if @isQuickbuild return true else if @isHyperspace return exportObj.hyperspaceCheck(item_data, @faction, shipCheck) else if (not @isEpic) return exportObj.epicExclusions(item_data) else return true getAvailableShipsMatching: (term='',sorted = true, collection_only = false) -> ships = [] for ship_name, ship_data of exportObj.ships if @isOurFaction(ship_data.factions) and (@matcher(ship_data.name, term) or (ship_data.display_name and @matcher(ship_data.display_name, term))) if (@isItemAvailable(ship_data, true)) if (not collection_only or (@collection? and (@collection.checks.collectioncheck == "true") and @collection.checkShelf('ship', ship_data.name))) ships.push id: ship_data.name text: if ship_data.display_name then ship_data.display_name else ship_data.name name: ship_data.name display_name: ship_data.display_name canonical_name: ship_data.canonical_name xws: ship_data.xws icon: if ship_data.icon then ship_data.icon else ship_data.xws if sorted ships.sort exportObj.sortHelper return ships getAvailableShipsMatchingAndCheapEnough: (points, term='', sorted=false, collection_only = false) -> # returns a list of ships that have at least one pilot cheaper than the given points value possible_ships = @getAvailableShipsMatching(term, sorted, collection_only) cheap_ships = [] for ship in possible_ships pilots = @getAvailablePilotsForShipIncluding(ship.name, null, '', true) if pilots.length and pilots[0].points <= points cheap_ships.push(ship) return cheap_ships getAvailablePilotsForShipIncluding: (ship, include_pilot, term='', sorted = true, ship_selector = null) -> # Returns data formatted for Select2 retval = [] if not @isQuickbuild # select available pilots according to ususal pilot selection available_faction_pilots = (pilot for pilot_name, pilot of exportObj.pilots when (not ship? or pilot.ship == ship) and @isOurFaction(pilot.faction) and (@matcher(pilot_name, term) or (pilot.display_name and @matcher(pilot.display_name, term)) ) and (@isItemAvailable(pilot, true))) eligible_faction_pilots = (pilot for pilot_name, pilot of available_faction_pilots when (not pilot.unique? or pilot not in @uniques_in_use['Pilot'] or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()) and (not pilot.max_per_squad? or @countPilots(pilot.canonical_name) < pilot.max_per_squad or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()) and (not pilot.restriction_func? or pilot.restriction_func((builder: @) , pilot))) # Re-add selected pilot if include_pilot? and include_pilot.unique? and (@matcher(include_pilot.name, term) or (include_pilot.display_name and @matcher(include_pilot.display_name, term)) ) eligible_faction_pilots.push include_pilot retval = ({ id: pilot.id, text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then pilot.skill + ' - ' else ''}#{if pilot.display_name then pilot.display_name else pilot.name} (#{pilot.points})", points: pilot.points, ship: pilot.ship, name: pilot.name, display_name: pilot.display_name, disabled: pilot not in eligible_faction_pilots } for pilot in available_faction_pilots) else # select according to quickbuild cards # filter for faction and ship quickbuilds_matching_ship_and_faction = (quickbuild for id, quickbuild of exportObj.quickbuildsById when (not ship? or quickbuild.ship == ship) and @isOurFaction(quickbuild.faction) and (@matcher(quickbuild.pilot, term) or (exportObj.pilots[quickbuild.pilot].display_name? and @matcher(exportObj.pilots[quickbuild.pilot].display_name, term)) )) # create a list of the uniques belonging to the currently selected pilot uniques_in_use_by_pilot_in_use = [] if include_pilot? and include_pilot != -1 include_quickbuild = exportObj.quickbuildsById[include_pilot] include_pilot_pilot = exportObj.pilots[include_quickbuild.pilot] if include_pilot_pilot.unique? uniques_in_use_by_pilot_in_use.push include_pilot_pilot for other in (exportObj.pilotsByUniqueName[include_pilot_pilot.canonical_name.getXWSBaseName()] or []) if other? uniques_in_use_by_pilot_in_use.push other for include_upgrade_name in include_quickbuild.upgrades ? [] include_upgrade = exportObj.upgrades[include_upgrade_name] if include_upgrade.unique? uniques_in_use_by_pilot_in_use.push other for other in (exportObj.pilotsByUniqueName[include_upgrade.canonical_name.getXWSBaseName()] or []) if other? uniques_in_use_by_pilot_in_use.push other if include_upgrade.solitary? uniques_in_use_by_pilot_in_use.push include_upgrade.slot # we should also add upgrades with the same unique name like some selected upgrades or the pilot. However, finding them is teadious # we should also add uniques used by a linked ship. however, while it is easy to allow selecting them, it is harder to properly add them - as one need to make sure the order of selecting ship + linked ship matters # filter for uniques in use allowed_quickbuilds_containing_uniques_in_use = [] loop: for id, quickbuild of quickbuilds_matching_ship_and_faction if exportObj.pilots[quickbuild.pilot]?.unique? and exportObj.pilots[quickbuild.pilot] in @uniques_in_use.Pilot and not (exportObj.pilots[quickbuild.pilot] in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id continue if exportObj.pilots[quickbuild.pilot]?.max_per_squad? and @countPilots(exportObj.pilots[quickbuild.pilot].canonical_name) >= exportObj.pilots[quickbuild.pilot].max_per_squad and not (exportObj.pilots[quickbuild.pilot] in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id continue if quickbuild.upgrades? for upgrade in quickbuild.upgrades upgradedata = exportObj.upgrades[upgrade] if not upgradedata? console.log("There was an Issue including the upgrade " + upgrade + " in some quickbuild. Please report that Issue!") continue if upgradedata.unique? and upgradedata in @uniques_in_use.Upgrade and not (upgradedata in uniques_in_use_by_pilot_in_use) # check, if unique is used by this ship or it's linked ship if ship_selector == null or not (upgrade in exportObj.quickbuildsById[ship_selector.quickbuildId].upgrades or (ship_selector.linkedShip and upgrade in (exportObj.quickbuildsById[ship_selector.linkedShip?.quickbuildId].upgrades ? []))) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id break # check if solitary type is already claimed if upgradedata.solitary? and upgradedata.slot in @uniques_in_use['Slot'] and not (upgradedata.slot in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id break retval = ({id: quickbuild.id, text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then exportObj.pilots[quickbuild.pilot].skill + ' - ' else ''}#{if exportObj.pilots[quickbuild.pilot].display_name then exportObj.pilots[quickbuild.pilot].display_name else quickbuild.pilot}#{quickbuild.suffix} (#{quickbuild.threat})", points: quickbuild.threat, ship: quickbuild.ship, disabled: quickbuild.id in allowed_quickbuilds_containing_uniques_in_use} for quickbuild in quickbuilds_matching_ship_and_faction) if sorted retval = retval.sort exportObj.sortHelper retval dfl_filter_func = -> true countUpgrades: (canonical_name) -> # returns number of upgrades with given canonical name equipped count = 0 for ship in @ships for upgrade in ship.upgrades if upgrade?.data?.canonical_name == canonical_name count++ count countPilots: (canonical_name) -> # returns number of pilots with given canonical name count = 0 for ship in @ships if ship?.pilot?.canonical_name.getXWSBaseName() == canonical_name.getXWSBaseName() count++ count isShip: (ship, name) -> # console.log "returning #{f} #{name}" if ship instanceof Array for f in ship if f == name return true false else ship == name getAvailableUpgradesIncluding: (slot, include_upgrade, ship, this_upgrade_obj, term='', filter_func=@dfl_filter_func, sorted=true) -> # Returns data formatted for Select2 upgrades_in_use = (upgrade.data for upgrade in ship.upgrades) available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgrades when exportObj.slotsMatching(upgrade.slot, slot) and ( @matcher(upgrade_name, term) or (upgrade.display_name and @matcher(upgrade.display_name, term)) ) and (not upgrade.ship? or @isShip(upgrade.ship, ship.data.name)) and (not upgrade.faction? or @isOurFaction(upgrade.faction, ship.pilot.faction)) and (@isItemAvailable(upgrade))) # available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgrades when exportObj.slotsMatching(upgrade.slot, slot) and ( @matcher(upgrade_name, term) or (upgrade.display_name and @matcher(upgrade.display_name, term)) ) and (not upgrade.ship? or @isShip(upgrade.ship, ship.data.name)) and (not upgrade.faction? or ((@faction != "All") and @isOurFaction(upgrade.faction)) or ((@faction == "All") and (not ship.pilot? or (ship.pilot.faction == upgrade.faction)))) and (@isItemAvailable(upgrade))) if filter_func != @dfl_filter_func available_upgrades = (upgrade for upgrade in available_upgrades when filter_func(upgrade)) eligible_upgrades = (upgrade for upgrade_name, upgrade of available_upgrades when (not upgrade.unique? or upgrade not in @uniques_in_use['Upgrade']) and (not (ship? and upgrade.restrictions?) or ship.restriction_check(upgrade.restrictions, this_upgrade_obj)) and upgrade not in upgrades_in_use and ((not upgrade.max_per_squad?) or ship.builder.countUpgrades(upgrade.canonical_name) < upgrade.max_per_squad) and (not upgrade.solitary? or (upgrade.slot not in @uniques_in_use['Slot'] or include_upgrade?.solitary?))) for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?) eligible_upgrades.removeItem equipped_upgrade # Re-enable selected upgrade if include_upgrade? and ((( @matcher(include_upgrade.name, term) or (include_upgrade.display_name and @matcher(include_upgrade.display_name, term))) ))# or current_upgrade_forcibly_removed) # available_upgrades.push include_upgrade eligible_upgrades.push include_upgrade retval = ({ id: upgrade.id, text: "#{if upgrade.display_name then upgrade.display_name else upgrade.name} (#{this_upgrade_obj.getPoints(upgrade)}#{if upgrade.pointsarray then '*' else ''})", points: this_upgrade_obj.getPoints(upgrade), name: upgrade.name, display_name: upgrade.display_name, disabled: upgrade not in eligible_upgrades } for upgrade in available_upgrades) if sorted retval = retval.sort exportObj.sortHelper # Possibly adjust the upgrade if this_upgrade_obj?adjustment_func? (this_upgrade_obj.adjustment_func(upgrade) for upgrade in retval) else retval getSquadDialsAsHTML: () -> dialHTML = "" added_dials = {} for ship in @ships if ship.pilot? # There is always one "empty" ship at the bottom of each squad, that we want to skip. maneuvers_unmodified = ship.data.maneuvers maneuvers_modified = ship.effectiveStats().maneuvers if not added_dials[ship.data.name]? or not (maneuvers_modified.toString() in added_dials[ship.data.name]) # we only want to add each dial once per ship (if two ships share a dial, add two copies of the dial) added_dials[ship.data.name] = (added_dials[ship.data.name] ? []).concat [maneuvers_modified.toString()] # save maneuver as string, as that is easier to compare than arrays (if e.g. two ships of same type, one with and one without R4 are in a squad, we add 2 dials) dialHTML += '<div class="fancy-dial">' + """<h4 class="ship-name-dial">#{if ship.data.display_name? then ship.data.display_name else ship.data.name}""" + """#{if maneuvers_modified.toString() != maneuvers_unmodified.toString() then " (upgraded)" else ""}</h4>""" + @getManeuverTableHTML(maneuvers_modified, maneuvers_unmodified) + '</div>' return """ <div class="print-dials-container"> #{dialHTML} </div> """ # dialHTML = @builder.getManeuverTableHTML(effective_stats.maneuvers, @data.maneuvers) # Converts a maneuver table for into an HTML table. getManeuverTableHTML: (maneuvers, baseManeuvers) -> if not maneuvers? or maneuvers.length == 0 return "Missing maneuver info." # Preprocess maneuvers to see which bearings are never used so we # don't render them. bearings_without_maneuvers = [0...maneuvers[0].length] for bearings in maneuvers for difficulty, bearing in bearings if difficulty > 0 bearings_without_maneuvers.removeItem bearing # console.log "bearings without maneuvers:" # console.dir bearings_without_maneuvers outTable = "<table><tbody>" for speed in [maneuvers.length - 1 .. 0] haveManeuver = false for v in maneuvers[speed] if v > 0 haveManeuver = true break continue if not haveManeuver outTable += "<tr><td>#{speed}</td>" for turn in [0 ... maneuvers[speed].length] continue if turn in bearings_without_maneuvers outTable += "<td>" if maneuvers[speed][turn] > 0 color = switch maneuvers[speed][turn] when 1 then "dodgerblue" when 2 then "white" when 3 then "red" when 4 then "purple" # we need this to change the color to b/w in case we want to print b/w maneuverClass = switch maneuvers[speed][turn] when 1 then "svg-blue-maneuver" when 2 then "svg-white-maneuver" when 3 then "svg-red-maneuver" when 4 then "svg-purple-maneuver" outTable += """<svg xmlns="http://www.w3.org/2000/svg" width="30px" height="30px" viewBox="0 0 200 200">""" outlineColor = "black" maneuverClass2 = "svg-base-maneuver" if maneuvers[speed][turn] != baseManeuvers[speed][turn] outlineColor = "DarkSlateGrey" # highlight manuevers modified by another card (e.g. R2 Astromech makes all 1 & 2 speed maneuvers green) maneuverClass2 = "svg-modified-maneuver" if speed == 0 and turn == 2 outTable += """<rect class="svg-maneuver-stop #{maneuverClass} #{maneuverClass2}" x="50" y="50" width="100" height="100" style="fill:#{color}" />""" else transform = "" className = "" switch turn when 0 # turn left linePath = "M160,180 L160,70 80,70" trianglePath = "M80,100 V40 L30,70 Z" when 1 # bank left linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(-5 -15) rotate(45 70 90)' " when 2 # straight linePath = "M100,180 L100,100 100,80" trianglePath = "M70,80 H130 L100,30 Z" when 3 # bank right linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(5 -15) rotate(-45 130 90)' " when 4 # turn right linePath = "M40,180 L40,70 120,70" trianglePath = "M120,100 V40 L170,70 Z" when 5 # k-turn/u-turn linePath = "M50,180 L50,100 C50,10 140,10 140,100 L140,120" trianglePath = "M170,120 H110 L140,180 Z" when 6 # segnor's loop left linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(0 50)'" when 7 # segnor's loop right linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(0 50)'" when 8 # tallon roll left linePath = "M160,180 L160,70 80,70" trianglePath = "M60,100 H100 L80,140 Z" when 9 # tallon roll right linePath = "M40,180 L40,70 120,70" trianglePath = "M100,100 H140 L120,140 Z" when 10 # backward left linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(5 -15) rotate(-45 130 90)' " className = 'backwards' when 11 # backward straight linePath = "M100,180 L100,100 100,80" trianglePath = "M70,80 H130 L100,30 Z" className = 'backwards' when 12 # backward right linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(-5 -15) rotate(45 70 90)' " className = 'backwards' outTable += $.trim """ <g class="maneuver #{className}"> <path class = 'svg-maneuver-outer #{maneuverClass} #{maneuverClass2}' stroke-width='25' fill='none' stroke='#{outlineColor}' d='#{linePath}' /> <path class = 'svg-maneuver-triangle #{maneuverClass} #{maneuverClass2}' d='#{trianglePath}' fill='#{color}' stroke-width='5' stroke='#{outlineColor}' #{transform}/> <path class = 'svg-maneuver-inner #{maneuverClass} #{maneuverClass2}' stroke-width='15' fill='none' stroke='#{color}' d='#{linePath}' /> </g> """ outTable += "</svg>" outTable += "</td>" outTable += "</tr>" outTable += "</tbody></table>" outTable formatActions: (actions,seperation,keyword=[]) -> action_icons = [] for action in actions color = "" prefix = seperation if "Droid" in keyword action = action.replace('Focus', 'Calculate') # Search and filter each type of action by its prefix and then reformat it for html if action.search('> ') != -1 action = action.replace(/> /gi, '') prefix = """ <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> """ if action.search('F-') != -1 color = "force " action = action.replace(/F-/gi, '') else if action.search('R-') != -1 color = "red " action = action.replace(/R-/gi, '') action = action.toLowerCase().replace(/[^0-9a-z]/gi, '') action_icons.push """#{prefix}<i class="xwing-miniatures-font #{color}xwing-miniatures-font-#{action}"></i>""" actionlist = action_icons.join '' return actionlist.replace(seperation,'') showTooltip: (type, data, additional_opts, container = @info_container, force_update = false) -> if data != @tooltip_currently_displaying or force_update switch type when 'Ship' # we get all pilots for the ship, to display stuff like available slots which are treated as pilot properties, not ship properties (which makes sense, as they depend on the pilot, e.g. talent or force slots) possible_inis = [] slot_types = {} # one number per slot: 0: not available for that ship. 1: always available for that ship. 2: available for some pilots on that ship. 3: slot two times availabel for that ship 4: slot one or two times available (depending on pilot) 5: slot zero to two times available 6: slot three times available (no mixed-case implemented) -1: undefined for slot of exportObj.upgradesBySlotCanonicalName slot_types[slot] = -1 for name, pilot of exportObj.pilots if pilot.ship != data.name continue if not (pilot.skill in possible_inis) possible_inis.push(pilot.skill) for slot, state of slot_types switch pilot.slots.filter((item) => item == slot).length when 1 switch state when -1 slot_types[slot] = 1 when 0 slot_types[slot] = 2 when 3 slot_types[slot] = 4 when 0 switch state when -1 slot_types[slot] = 0 when 1 slot_types[slot] = 2 when 3,4 slot_types[slot] = 5 when 2 switch state when -1 slot_types[slot] = 3 when 0,2 slot_types[slot] = 5 when 1 slot_types[slot] = 4 when 3 slot_types[slot] = 6 possible_inis.sort() container.find('.info-type').text type container.find('.info-name').html """#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" if @collection?.counts? ship_count = @collection.counts?.ship?[data.name] ? 0 container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() first = true inis = String(possible_inis[0]) for ini in possible_inis if not first inis += ", " + ini first = false container.find('tr.info-skill td.info-data').text inis container.find('tr.info-skill').show() container.find('tr.info-engagement').hide() container.find('tr.info-attack td.info-data').text(data.attack) container.find('tr.info-attack-bullseye td.info-data').text(data.attackbull) container.find('tr.info-attack-fullfront td.info-data').text(data.attackf) container.find('tr.info-attack-left td.info-data').text(data.attackl) container.find('tr.info-attack-right td.info-data').text(data.attackr) container.find('tr.info-attack-back td.info-data').text(data.attackb) container.find('tr.info-attack-turret td.info-data').text(data.attackt) container.find('tr.info-attack-doubleturret td.info-data').text(data.attackdt) container.find('tr.info-attack').toggle(data.attack?) container.find('tr.info-attack-bullseye').toggle(data.attackbull?) container.find('tr.info-attack-fullfront').toggle(data.attackf?) container.find('tr.info-attack-left').toggle(data.attackl?) container.find('tr.info-attack-right').toggle(data.attackr?) container.find('tr.info-attack-back').toggle(data.attackb?) container.find('tr.info-attack-turret').toggle(data.attackt?) container.find('tr.info-attack-doubleturret').toggle(data.attackdt?) container.find('tr.info-ship').hide() if data.large? container.find('tr.info-base td.info-data').text "Large" else if data.medium? container.find('tr.info-base td.info-data').text "Medium" else if data.huge? container.find('tr.info-base td.info-data').text "Huge" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(data.attack_icon ? 'xwing-miniatures-font-attack') container.find('tr.info-range').hide() container.find('tr.info-agility td.info-data').text(data.agility) container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text(data.hull) container.find('tr.info-hull').show() recurringicon = '' if data.shieldrecurr? count = 0 while count < data.shieldrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-shields td.info-data').html (data.shields + recurringicon) container.find('tr.info-shields').show() recurringicon = '' if data.energyrecurr? count = 0 while count < data.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-energy td.info-data').html (data.energy + recurringicon) container.find('tr.info-energy').toggle(data.energy?) # One may want to check for force sensitive pilots and display the possible values here (like done for ini), but I'll skip this for now. container.find('tr.info-force').hide() container.find('tr.info-charge').hide() container.find('tr.info-actions td.info-data').html @formatActions(data.actions, ", ", data.keyword ? []) container.find('tr.info-actions').show() # Display all available slots, put brackets around slots that are only available for some pilots container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html(((if state == 1 then exportObj.translate(@language, 'sloticon', slot) else (if state == 2 then '('+exportObj.translate(@language, 'sloticon', slot)+')' else (if state == 3 then (exportObj.translate(@language, 'sloticon', slot) + exportObj.translate(@language, 'sloticon', slot)) else (if state == 4 then (exportObj.translate(@language, 'sloticon', slot) + '(' + exportObj.translate(@language, 'sloticon', slot) + ')') else (if state == 5 then ('(' + exportObj.translate(@language, 'sloticon', slot) + exportObj.translate(@language, 'sloticon', slot) + ')') else (if state == 6 then (exportObj.translate(@language, 'sloticon',slot) + exportObj.translate(@language, 'sloticon',slot) + exportObj.translate(@language, 'sloticon',slot)))))))) for slot, state of slot_types).join(' ') or 'None') container.find('p.info-text').hide() container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(data.maneuvers, data.maneuvers)) sources = (exportObj.translate(@language, 'sources', source) for source in data.sources).sort() container.find('.info-sources.info-data').text if (sources.length > 1) or (not ('Loose Ships' in sources)) then (if sources.length > 0 then sources.join(', ') else exportObj.translate(@language, 'ui', 'unreleased')) else "Only available from 1st edition" container.find('.info-sources').show() when 'Pilot' container.find('.info-type').text type container.find('.info-sources.info-data').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') container.find('.info-sources').show() if @collection?.counts? pilot_count = @collection.counts?.pilot?[data.name] ? 0 ship_count = @collection.counts.ship?[data.ship] ? 0 container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() # if the pilot is already selected and has uprades, some stats may be modified if additional_opts?.effectiveStats? effective_stats = additional_opts.effectiveStats() #logic to determine how many dots to use for uniqueness if data.unique? uniquedots = "&middot;&nbsp;" else if data.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" container.find('.info-name').html """#{uniquedots}#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" restriction_info = @restriction_text(data) + @upgrade_effect(data) if restriction_info != '' container.find('p.info-restrictions').html restriction_info ? '' container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html data.text ? '' container.find('p.info-text').show() ship = exportObj.ships[data.ship] container.find('tr.info-ship td.info-data').text data.ship container.find('tr.info-ship').show() if ship.large? container.find('tr.info-base td.info-data').text "Large" else if ship.medium? container.find('tr.info-base td.info-data').text "Medium" else if ship.huge? container.find('tr.info-base td.info-data').text "Huge" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() container.find('tr.info-skill td.info-data').text data.skill container.find('tr.info-skill').show() if data.engagement? container.find('tr.info-engagement td.info-data').text data.engagement container.find('tr.info-engagement').show() else container.find('tr.info-engagement').hide() # for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList # container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-attack') container.find('tr.info-attack td.info-data').text statAndEffectiveStat((data.ship_override?.attack ? ship.attack), effective_stats, 'attack') container.find('tr.info-attack').toggle(ship.attack? or effective_stats?.attack?) container.find('tr.info-attack-fullfront td.info-data').text statAndEffectiveStat((data.ship_override?.attackf ? ship.attackf), effective_stats, 'attackf') container.find('tr.info-attack-fullfront').toggle(ship.attackf? or effective_stats?.attackf?) container.find('tr.info-attack-bullseye td.info-data').text statAndEffectiveStat((data.ship_override?.attackbull ? ship.attackbull), effective_stats, 'attackbull') container.find('tr.info-attack-bullseye').toggle(ship.attackbull? or effective_stats?.attackbull?) container.find('tr.info-attack-left td.info-data').text statAndEffectiveStat((data.ship_override?.attackl ? ship.attackl), effective_stats, 'attackl') container.find('tr.info-attack-left').toggle(ship.attackl? or effective_stats?.attackl?) container.find('tr.info-attack-right td.info-data').text statAndEffectiveStat((data.ship_override?.attackr ? ship.attackr), effective_stats, 'attackr') container.find('tr.info-attack-right').toggle(ship.attackr? or effective_stats?.attackr?) container.find('tr.info-attack-back td.info-data').text statAndEffectiveStat((data.ship_override?.attackb ? ship.attackb), effective_stats, 'attackb') container.find('tr.info-attack-back').toggle(ship.attackb? or effective_stats?.attackb?) container.find('tr.info-attack-turret td.info-data').text statAndEffectiveStat((data.ship_override?.attackt ? ship.attackt), effective_stats, 'attackt') container.find('tr.info-attack-turret').toggle(ship.attackt? or effective_stats?.attackt?) container.find('tr.info-attack-doubleturret td.info-data').text statAndEffectiveStat((data.ship_override?.attackdt ? ship.attackdt), effective_stats, 'attackdt') container.find('tr.info-attack-doubleturret').toggle(ship.attackdt? or effective_stats?.attackdt?) container.find('tr.info-range').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-agility td.info-data').text statAndEffectiveStat((data.ship_override?.agility ? ship.agility), effective_stats, 'agility') container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text statAndEffectiveStat((data.ship_override?.hull ? ship.hull), effective_stats, 'hull') container.find('tr.info-hull').show() recurringicon = '' if ship.shieldrecurr? count = 0 while count < ship.shieldrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-shields td.info-data').html (statAndEffectiveStat((data.ship_override?.shields ? ship.shields), effective_stats, 'shields') + recurringicon) container.find('tr.info-shields').show() recurringicon = '' if ship.energyrecurr? count = 0 while count < ship.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-energy td.info-data').html (statAndEffectiveStat((data.ship_override?.energy ? ship.energy), effective_stats, 'energy') + recurringicon) container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?) if (effective_stats?.force? and effective_stats.force > 0) or data.force? container.find('tr.info-force td.info-data').html (statAndEffectiveStat((data.ship_override?.force ? data.force), effective_stats, 'force') + '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').show() else container.find('tr.info-force').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').show() else container.find('tr.info-charge').hide() if effective_stats?.actions? container.find('tr.info-actions td.info-data').html @formatActions(data.ship_override?.actions ? effective_stats.actions, ", ") else container.find('tr.info-actions td.info-data').html @formatActions(data.ship_override?.actions ? ship.actions, ", ", data.keyword ? []) container.find('tr.info-actions').show() if @isQuickbuild container.find('tr.info-upgrades').hide() else container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html((exportObj.translate(@language, 'sloticon', slot) for slot in data.slots).join(' ') or 'None') container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(effective_stats?.maneuvers ? ship.maneuvers, ship.maneuvers)) when 'Quickbuild' container.find('.info-type').text 'Quickbuild' container.find('.info-sources').hide() # there are different sources for the pilot and the upgrade cards, so we won't display any container.find('.info-collection').hide() # same here, hard to give a single number telling a user how often he ownes all required cards pilot = exportObj.pilots[data.pilot] ship = exportObj.ships[data.ship] #logic to determine how many dots to use for uniqueness if pilot.unique? uniquedots = "&middot;&nbsp;" else if pilot.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" container.find('.info-name').html """#{uniquedots}#{if pilot.display_name then pilot.display_name else pilot.name}#{if data.suffix? then data.suffix else ""}#{if exportObj.isReleased(pilot) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" restriction_info = @restriction_text(data) + @upgrade_effect(data) if restriction_info != '' container.find('p.info-restrictions').html restriction_info ? '' container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html pilot.text ? '' container.find('p.info-text').show() container.find('tr.info-ship td.info-data').text data.ship container.find('tr.info-ship').show() if ship.large? container.find('tr.info-base td.info-data').text "Large" else if ship.medium? container.find('tr.info-base td.info-data').text "Medium" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() container.find('tr.info-skill td.info-data').text pilot.skill container.find('tr.info-skill').show() container.find('tr.info-engagement td.info-data').text pilot.skill container.find('tr.info-engagement').show() container.find('tr.info-attack td.info-data').text(pilot.ship_override?.attack ? ship.attack) container.find('tr.info-attack').toggle(pilot.ship_override?.attack? or ship.attack?) container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf) container.find('tr.info-attack-fullfront').toggle(ship.attackf?) container.find('tr.info-attack-bullseye td.info-data').text(ship.attackbull) container.find('tr.info-attack-bullseye').toggle(ship.attackbull?) container.find('tr.info-attack-left td.info-data').text(ship.attackl) container.find('tr.info-attack-left').toggle(ship.attackl?) container.find('tr.info-attack-right td.info-data').text(ship.attackr) container.find('tr.info-attack-right').toggle(ship.attackr?) container.find('tr.info-attack-back td.info-data').text(ship.attackb?) container.find('tr.info-attack-back').toggle(ship.attackb?) container.find('tr.info-attack-turret td.info-data').text(ship.attackt?) container.find('tr.info-attack-turret').toggle(ship.attackt?) container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt) container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?) # for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList # container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-frontarc') container.find('tr.info-energy td.info-data').text(pilot.ship_override?.energy ? ship.energy) container.find('tr.info-energy').toggle(pilot.ship_override?.energy? or ship.energy?) container.find('tr.info-range').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-agility td.info-data').text(pilot.ship_override?.agility ? ship.agility) container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text(pilot.ship_override?.hull ? ship.hull) container.find('tr.info-hull').show() container.find('tr.info-shields td.info-data').text(pilot.ship_override?.shields ? ship.shields) container.find('tr.info-shields').show() if effective_stats?.force? or data.force? container.find('tr.info-force td.info-data').html ((pilot.ship_override?.force ? pilot.force)+ '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').show() else container.find('tr.info-force').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').show() else container.find('tr.info-charge').hide() container.find('tr.info-actions td.info-data').html @formatActions(pilot.ship_override?.actions ? exportObj.ships[data.ship].actions, ", ", pilot.keyword ? []) container.find('tr.info-actions').show() container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html(((if exportObj.upgrades[upgrade].display_name? then exportObj.upgrades[upgrade].display_name else upgrade) for upgrade in (data.upgrades ? [])).join(', ') or 'None') container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(ship.maneuvers, ship.maneuvers)) when 'Addon' container.find('.info-type').text additional_opts.addon_type container.find('.info-sources.info-data').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') container.find('.info-sources').show() #logic to determine how many dots to use for uniqueness if data.unique? uniquedots = "&middot;&nbsp;" else if data.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" if @collection?.counts? addon_count = @collection.counts?['upgrade']?[data.name] ? 0 container.find('.info-collection').text """You have #{addon_count} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() container.find('.info-name').html """#{uniquedots}#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" if data.pointsarray? point_info = "<i><b>Point cost:</b> " + data.pointsarray + " when " if data.variableagility? and data.variableagility point_info += "agility is " + [0..data.pointsarray.length-1] else if data.variableinit? and data.variableinit point_info += "initiative is " + [0..data.pointsarray.length-1] else if data.variablebase? and data.variablebase point_info += " base size is small, medium, large or huge" point_info += "</i>" restriction_info = @restriction_text(data) + @upgrade_effect(data) if point_info? or (restriction_info != '') if point_info? and (restriction_info != '') point_info += "<br/>" container.find('p.info-restrictions').html (point_info ? '') + restriction_info container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html (data.text ? '') container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-engagement').hide() if data.energy? container.find('tr.info-energy td.info-data').text data.energy container.find('tr.info-energy').show() else container.find('tr.info-energy').hide() if data.attack? container.find('tr.info-attack td.info-data').text data.attack container.find('tr.info-attack').show() else container.find('tr.info-attack').hide() if data.attackt? container.find('tr.info-attack-turret td.info-data').text data.attackt container.find('tr.info-attack-turret').show() else container.find('tr.info-attack-turret').hide() if data.attackr? container.find('tr.info-attack-right td.info-data').text data.attackr container.find('tr.info-attack-right').show() else container.find('tr.info-attack-right').hide() if data.attackl? container.find('tr.info-attack-left td.info-data').text data.attackl container.find('tr.info-attack-left').show() else container.find('tr.info-attack-right').hide() if data.attackdt? container.find('tr.info-attack-doubleturret td.info-data').text data.attackdt container.find('tr.info-attack-doubleturret').show() else container.find('tr.info-attack-doubleturret').hide() if data.attackbull? container.find('tr.info-attack-bullseye td.info-data').text data.attackbull container.find('tr.info-attack-bullseye').show() else container.find('tr.info-attack-bullseye').hide() if data.attackf? container.find('tr.info-attack-fullfront td.info-data').text data.attackf container.find('tr.info-attack-fullfront').show() else container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-right').hide() container.find('tr.info-attack-left').hide() container.find('tr.info-attack-back').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').toggle(data.charge?) if data.range? container.find('tr.info-range td.info-data').text data.range container.find('tr.info-range').show() else container.find('tr.info-range').hide() if data.rangebonus? container.find('td.info-rangebonus').show() else container.find('td.info-rangebonus').hide() container.find('tr.info-force td.info-data').html (data.force + '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').toggle(data.force?) container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() when 'Rules' container.find('.info-type').hide() container.find('.info-sources').hide() container.find('.info-collection').hide() container.find('.info-name').html data.name container.find('.info-name').show() container.find('p.info-restrictions').hide() container.find('p.info-text').html data.text container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() container.find('tr.info-energy').hide() container.find('tr.info-attack').hide() container.find('tr.info-attack-turret').hide() container.find('tr.info-attack-bullseye').hide() container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-back').hide() container.find('tr.info-attack-doubleturret').hide() container.find('tr.info-charge').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-range').hide() container.find('tr.info-force').hide() when 'MissingStuff' container.find('.info-type').text "List of Missing items" container.find('.info-sources').hide() container.find('.info-collection').hide() container.find('.info-name').html "Missing items" container.find('.info-name').show() missingStuffInfoText = "To field this squad you need the following additional items: <ul>" for item in data missingStuffInfoText += """<li><strong>#{(if item.display_name? then item.display_name else item.name)}</strong> (""" first = true for source in item.sources if not first missingStuffInfoText += ", " missingStuffInfoText += source first = false missingStuffInfoText += ")</li>" missingStuffInfoText +="</ul>" container.find('p.info-restrictions').hide() container.find('p.info-text').html missingStuffInfoText container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() container.find('tr.info-energy').hide() container.find('tr.info-attack').hide() container.find('tr.info-attack-turret').hide() container.find('tr.info-attack-bullseye').hide() container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-back').hide() container.find('tr.info-attack-doubleturret').hide() container.find('tr.info-charge').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-range').hide() container.find('tr.info-force').hide() if container != @mobile_tooltip_modal container.show() @tooltip_currently_displaying = data # fix card viewer to view, if it is fully visible (it might not be e.g. on mobile devices. In that case keep it on its static position, so you can scroll to see it) if $(window).width() >= 768 well = container.find('.info-well') if $.isElementInView(well, true) well.css('position','fixed') else well.css('position','static') _randomizerLoopBody: (data) => if data.keep_running #console.log "Current points: #{@total_points} of #{data.max_points}, iteration=#{data.iterations} of #{data.max_iterations}, keep_running=#{data.keep_running}" if data.max_points - @total_points <= data.bid_goal and @total_points <= data.max_points # Hit bid range #console.log "Points reached exactly" data.keep_running = false else if @total_points < data.max_points #console.log "Need to add something" # Add something # Possible options: ship or empty addon slot unused_addons = [] for ship in @ships for upgrade in ship.upgrades unused_addons.push upgrade unless upgrade.data? or (upgrade.occupied_by? and upgrade.occupied_by != null) # 0 is ship, otherwise addon idx = $.randomInt(data.ships_or_upgrades + unused_addons.length) if idx < data.ships_or_upgrades or unused_addons.length == 0 # Add random ship #console.log "Add ship" available_ships = @getAvailableShipsMatchingAndCheapEnough(data.max_points - @total_points, '', false, data.collection_only) if available_ships.length == 0 if unused_addons.length > 0 idx = $.randomInt(unused_addons.length) + data.ships_or_upgrades else available_ships = @getAvailableShipsMatching('', false, data.collection_only) if (available_ships.length > 0) and ((@ships.length < data.ship_limit) or (data.ship_limit == 0)) ship_type = available_ships[$.randomInt available_ships.length].name available_pilots = @getAvailablePilotsForShipIncluding(ship_type) if available_pilots.length == 0 # edge case: It might have been a ship selected, that has only unique pilots - which all have been already selected return pilot = available_pilots[$.randomInt available_pilots.length] if not pilot.disabled and (if @isQuickbuild then exportObj.pilots[exportObj.quickbuildsById[pilot.id].pilot] else exportObj.pilotsById[pilot.id]).sources.intersects(data.allowed_sources) and ((not data.collection_only) or @collection.checkShelf('pilot', (if @isQuickbuild then exportObj.quickbuildsById[pilot.id] else pilot.name))) new_ship = @addShip() new_ship.setPilotById pilot.id if idx >= data.ships_or_upgrades and unused_addons.length != 0 # Add upgrade #console.log "Add addon" addon = unused_addons[idx - data.ships_or_upgrades] switch addon.type when 'Upgrade' available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship, addon,'', @dfl_filter_func, sorted = false) when (exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources) and ((not data.collection_only) or @collection.checkShelf('upgrade', upgrade.name)))) upgrade = if available_upgrades.length > 0 then available_upgrades[$.randomInt available_upgrades.length] else undefined if upgrade and not upgrade.disabled addon.setById upgrade.id else throw new Error("Invalid addon type #{addon.type}") else #console.log "Need to remove something" # Remove something removable_things = [] for ship in @ships for _ in [0...(11-data.ships_or_upgrades)] removable_things.push ship for upgrade in ship.upgrades removable_things.push upgrade if upgrade.data? if removable_things.length > 0 thing_to_remove = removable_things[$.randomInt removable_things.length] #console.log "Removing #{thing_to_remove}" if thing_to_remove instanceof Ship @removeShip thing_to_remove else if thing_to_remove instanceof GenericAddon thing_to_remove.setData null else throw new Error("Unknown thing to remove #{thing_to_remove}") # continue the "loop" window.setTimeout @_makeRandomizerLoopFunc(data), 0 else #console.log "Clearing timer #{data.timer}, iterations=#{data.iterations}, keep_running=#{data.keep_running}" # we have to stop randomizing, but should do a final check on our point costs. while @total_points > data.max_points removable_things = [] for ship in @ships # removable_things.push ship for upgrade in ship.upgrades removable_things.push upgrade if upgrade.data? if removable_things.length == 0 for ship in @ships removable_things.push ship if removable_things.length > 0 thing_to_remove = removable_things[$.randomInt removable_things.length] #console.log "Removing #{thing_to_remove}" if thing_to_remove instanceof Ship @removeShip thing_to_remove else if thing_to_remove instanceof GenericAddon thing_to_remove.setData null else throw new Error("Unknown thing to remove #{thing_to_remove}") if data.fill_zero_pts for ship in @ships for addon in ship.upgrades continue unless not (addon.data? or (addon.occupied_by? and addon.occupied_by != null)) available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship, addon,'', @dfl_filter_func, sorted = false) when (exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources) and (upgrade.points < 1) and ((not data.collection_only) or @collection.checkShelf('upgrade', upgrade.name)))) upgrade = if available_upgrades.length > 0 then available_upgrades[$.randomInt available_upgrades.length] else undefined if upgrade and not upgrade.disabled addon.setById upgrade.id window.clearTimeout data.timer # Update all selectors for ship in @ships ship.updateSelections() @suppress_automatic_new_ship = false @addShip() _makeRandomizerLoopFunc: (data) => () => @_randomizerLoopBody(data) randomSquad: (max_points=200, allowed_sources=null, timeout_ms=1000, bid_goal=5, ship_limit=0, ships_or_upgrades=3, collection_only=true, fill_zero_pts=false) -> @backend_status.fadeOut 'slow' @suppress_automatic_new_ship = true if allowed_sources.length < 1 allowed_sources = null # Clear all existing ships while @ships.length > 0 @removeShip @ships[0] throw new Error("Ships not emptied") if @ships.length > 0 data = max_points: max_points bid_goal: bid_goal ship_limit: ship_limit ships_or_upgrades: ships_or_upgrades keep_running: true allowed_sources: allowed_sources ? exportObj.expansions collection_only: @collection? and (@collection.checks.collectioncheck == "true") and collection_only fill_zero_pts: fill_zero_pts stopHandler = () => #console.log "*** TIMEOUT *** TIMEOUT *** TIMEOUT ***" data.keep_running = false data.timer = window.setTimeout stopHandler , timeout_ms #console.log "Timer set for #{timeout_ms}ms, timer is #{data.timer}" window.setTimeout @_makeRandomizerLoopFunc(data), 0 @resetCurrentSquad() @current_squad.name = 'Random Squad' @container.trigger 'xwing-backend:squadNameChanged' setBackend: (backend) -> @backend = backend if @waiting_for_backend? for meth in @waiting_for_backend meth() upgrade_effect: (card) -> removestext = text = comma = '' if card.modifier_func statchange = attack: 0 attackf: 0 attackbull: 0 attackb: 0 attackt: 0 attackl: 0 attackr: 0 attackdt: 0 energy: 0 agility: 0 hull: 0 shields: 0 force: 0 actions: [] maneuvers: [0, 0] card.modifier_func(statchange) if statchange.attack != 0 text += comma + "%FRONTARC% (#{statchange.attack})" comma = ', ' if statchange.attackf != 0 text += comma + "%FULLFRONTARC% (#{statchange.attackf})" comma = ', ' if statchange.attackbull != 0 text += comma + "%BULLSEYEARC% (#{statchange.attackbull})" comma = ', ' if statchange.attackb != 0 text += comma + "%REARARC% (#{statchange.attackb})" comma = ', ' if statchange.attackt != 0 text += comma + "%SINGLETURRETARC% (#{statchange.attackt})" comma = ', ' if statchange.attackl != 0 text += comma + "%LEFTARC% (#{statchange.attackl})" comma = ', ' if statchange.attackr != 0 text += comma + "%RIGHTARC% (#{statchange.attackr})" comma = ', ' if statchange.attackdt != 0 text += comma + "%DOUBLETURRETARC% (#{statchange.attackdt})" comma = ', ' if statchange.energy != 0 text += comma + "%ENERGY% (#{statchange.energy})" comma = ', ' if statchange.agility != 0 text += comma + "%AGILITY% (#{statchange.agility})" comma = ', ' if statchange.hull != 0 text += comma + "%HULL% (#{statchange.hull})" comma = ', ' if statchange.shields != 0 text += comma + "%SHIELD% (#{statchange.shields})" comma = ', ' if statchange.actions.length > 0 text += comma + @formatActions(statchange.actions, ", ") comma = ', ' if card.confersAddons for addonname in card.confersAddons text += comma + "%#{addonname.slot.toUpperCase().replace(/[^a-z0-9]/gi, '')}%" comma = ', ' if card.unequips_upgrades comma = '' for slot in card.unequips_upgrades removestext += comma + "%#{slot.toUpperCase().replace(/[^a-z0-9]/gi, '')}%" comma = ', ' if text != '' data = text: "</br><b>Adds:</b> #{text}" if removestext != '' data.text += "</br><b>Removes:</b> #{removestext}" return exportObj.fixIcons(data) else return '' restriction_text: (card) -> uniquetext = comma = othertext = text = '' if card.restrictions for r in card.restrictions if r[0] == "orUnique" uniquetext = exportObj.translate(@language, 'restrictions', " or Squad Including") + " #{r[1]}" continue switch r[0] when "Base" text += comma + "#{r[1]} " + exportObj.translate(@language, 'restrictions', "Ship") when "Action" array = [r[1]] text += comma + @formatActions(array,"", []) when "Equipped" text += comma + "%#{r[1].toUpperCase().replace(/[^a-z0-9]/gi, '')}% Equipped" when "Slot" text += comma + exportObj.translate(@language, 'restrictions', "Extra") + " %#{r[1].toUpperCase().replace(/[^a-z0-9]/gi, '')}%" when "Keyword" text += comma + exportObj.translate(@language, 'restrictions', "#{r[1]}") when "AttackArc" text += comma + "%REARARC%" when "ShieldsGreaterThan" text += comma + "%SHIELD% > #{r[1]}" when "EnergyGreatterThan" text += comma + "%ENERGY% > #{r[1]}" when "InitiativeGreaterThan" text += comma + exportObj.translate(@language, 'restrictions', "Initiative") + " > #{r[1]}" when "InitiativeLessThan" text += comma + exportObj.translate(@language, 'restrictions', "Initiative")+ " < #{r[1]}" when "AgilityEquals" text += comma + exportObj.translate(@language, 'restrictions', "Agility") + " = #{r[1]}" when "isUnique" if r[1] == true text += comma + exportObj.translate(@language, 'restrictions', "Limited") else text += comma + exportObj.translate(@language, 'restrictions', "Non-Limited") when "Format" text += comma + exportObj.translate(@language, 'restrictions', "#{r[1]} Ship") when "Faction" othertext += comma + exportObj.translate(@language, 'faction', "#{r[1]}") comma = ', ' if not card.skill if othertext == '' if card.faction if card.faction instanceof Array for factionitem in card.faction othertext += comma + exportObj.translate(@language, 'faction', "#{factionitem}") comma = ' or ' else othertext += comma + exportObj.translate(@language, 'faction', "#{card.faction}") comma = ', ' if card.ship if card.ship instanceof Array for shipname in card.ship othertext += comma + shipname comma = ' or ' else othertext += comma + card.ship comma = ', ' if card.solitary othertext += comma + exportObj.translate(@language, 'faction', "Solitary") comma = ', ' if card.standardized othertext += comma + exportObj.translate(@language, 'faction', "Standardized") comma = ', ' text += othertext + uniquetext if text != '' data = text: "<i><b>" + exportObj.translate(@language, 'restrictions', "Restrictions") + ":</b> " + text + "</i>" return exportObj.fixIcons(data) else return '' describeSquad: -> if @getNotes().trim() == '' then ((ship.pilot.name for ship in @ships when ship.pilot?).join ', ') else @getNotes() listCards: -> card_obj = {} for ship in @ships if ship.pilot? card_obj[ship.pilot.name] = null for upgrade in ship.upgrades card_obj[upgrade.data.name] = null if upgrade.data? return Object.keys(card_obj).sort() getNotes: -> @notes.val() getTag: -> @tag.val() getObstacles: -> @current_obstacles isSquadPossibleWithCollection: -> # If the collection is uninitialized or empty, don't actually check it. if Object.keys(@collection?.expansions ? {}).length == 0 # console.log "collection not ready or is empty" return [true, []] else if @collection?.checks.collectioncheck != "true" # console.log "collection check not enabled" return [true, []] @collection.reset() validity = true missingStuff = [] for ship in @ships if ship.pilot? # Try to get both the physical model and the pilot card. ship_is_available = @collection.use('ship', ship.pilot.ship) pilot_is_available = @collection.use('pilot', ship.pilot.name) # console.log "#{@faction}: Ship #{ship.pilot.ship} available: #{ship_is_available}" # console.log "#{@faction}: Pilot #{ship.pilot.name} available: #{pilot_is_available}" validity = false unless ship_is_available and pilot_is_available missingStuff.push ship.data unless ship_is_available missingStuff.push ship.pilot unless pilot_is_available for upgrade in ship.upgrades if upgrade.data? upgrade_is_available = @collection.use('upgrade', upgrade.data.name) # console.log "#{@faction}: Upgrade #{upgrade.data.name} available: #{upgrade_is_available}" validity = false unless upgrade_is_available missingStuff.push upgrade.data unless upgrade_is_available [validity, missingStuff] checkCollection: -> # console.log "#{@faction}: Checking validity of squad against collection..." if @collection? [squadPossible, missingStuff] = @isSquadPossibleWithCollection() @collection_invalid_container.toggleClass 'd-none', squadPossible @collection_invalid_container.on 'mouseover', (e) => @showTooltip 'MissingStuff', missingStuff toXWS: -> # Often you will want JSON.stringify(builder.toXWS()) xws = description: @getNotes() faction: exportObj.toXWSFaction[@faction] name: @current_squad.name pilots: [] points: @total_points vendor: yasb: builder: 'YASB 2.0' builder_url: window.location.href.split('?')[0] link: @getPermaLink() version: '2.0.0' for ship in @ships if ship.pilot? xws.pilots.push ship.toXWS() # Associate multisection ships # This maps id to list of pilots it comprises multisection_id_to_pilots = {} last_id = 0 unmatched = (pilot for pilot in xws.pilots when pilot.multisection?) for _ in [0...(unmatched.length ** 2)] break if unmatched.length == 0 # console.log "Top of loop, unmatched: #{m.name for m in unmatched}" unmatched_pilot = unmatched.shift() unmatched_pilot.multisection_id ?= last_id++ multisection_id_to_pilots[unmatched_pilot.multisection_id] ?= [unmatched_pilot] break if unmatched.length == 0 # console.log "Finding matches for #{unmatched_pilot.name} (assigned id=#{unmatched_pilot.multisection_id})" matches = [] for candidate in unmatched # console.log "-> examine #{candidate.name}" if unmatched_pilot.name in candidate.multisection matches.push candidate unmatched_pilot.multisection.removeItem candidate.name candidate.multisection.removeItem unmatched_pilot.name candidate.multisection_id = unmatched_pilot.multisection_id # console.log "-> MATCH FOUND #{candidate.name}, assigned id=#{candidate.multisection_id}" multisection_id_to_pilots[candidate.multisection_id].push candidate if unmatched_pilot.multisection.length == 0 # console.log "-> No more sections to match for #{unmatched_pilot.name}" break for match in matches if match.multisection.length == 0 # console.log "Dequeue #{match.name} since it has no more sections to match" unmatched.removeItem match for pilot in xws.pilots delete pilot.multisection if pilot.multisection? obstacles = @getObstacles() if obstacles? and obstacles.length > 0 xws.obstacles = obstacles xws toMinimalXWS: -> # Just what's necessary xws = @toXWS() # Keep mandatory stuff only for own k, v of xws delete xws[k] unless k in ['faction', 'pilots', 'version'] for own k, v of xws.pilots delete xws[k] unless k in ['id', 'upgrades', 'multisection_id'] xws loadFromXWS: (xws, cb) -> success = null error = null if xws.version? version_list = (parseInt x for x in xws.version.split('.')) else version_list = [0,2] # Version tag is optional, so let's just assume it is some 2.0 xws if no version is given switch # Not doing backward compatibility pre-1.x when version_list > [0, 1] xws_faction = exportObj.fromXWSFaction[xws.faction] if @faction != xws_faction throw new Error("Attempted to load XWS for #{xws.faction} but builder is #{@faction}") if xws.name? @current_squad.name = xws.name if xws.description? @notes.val xws.description if xws.obstacles? @current_squad.additional_data.obstacles = xws.obstacles @suppress_automatic_new_ship = true @removeAllShips() success = true error = "" serialized_squad = "v8ZsZ200Z" # serialization version 7, standard squad, 200 points # serialization schema SHIPID:UPGRADEID,UPGRADEID,...,UPGRADEID:;SHIPID:UPGRADEID,... for pilot in xws.pilots new_ship = @addShip() # we add some backward compatibility here, to allow imports from Launch Bay Next Squad Builder # According to xws-spec, for 2nd edition we use id instead of name # however, we will accept a name instead of an id as well. if pilot.id pilotxws = pilot.id else if pilot.name pilotxws = pilot.name else success = false error = "Pilot without identifier" break # add pilot id if exportObj.pilotsByFactionXWS[xws_faction][pilotxws]? serialized_squad += exportObj.pilotsByFactionXWS[xws_faction][pilotxws][0].id else if exportObj.pilotsByUniqueName[pilotxws] and exportObj.pilotsByUniqueName[pilotxws].length == 1 serialized_squad += exportObj.pilotsByUniqueName[pilotxws][0].id else for key, possible_pilots of exportObj.pilotsByUniqueName for possible_pilot in possible_pilots if (possible_pilot.xws and possible_pilot.xws == pilotxws) or (not possible_pilot.xws and key == pilotxws) serialized_squad += possible_pilot.id break serialized_squad += "X" # add upgrade ids # Turn all the upgrades into a flat list so we can keep trying to add them addons = [] for upgrade_type, upgrade_canonicals of pilot.upgrades ? {} for upgrade_canonical in upgrade_canonicals # console.log upgrade_type, upgrade_canonical slot = null slot = exportObj.fromXWSUpgrade[upgrade_type] ? upgrade_type.capitalize() upgrade = exportObj.upgradesBySlotXWSName[slot][upgrade_canonical] ?= exportObj.upgradesBySlotCanonicalName[slot][upgrade_canonical] if not upgrade? console.log("Failed to load xws upgrade: " + upgrade_canonical) error += "Skipped upgrade " + upgrade_canonical success = false continue serialized_squad += upgrade.id serialized_squad += "W" serialized_squad += "XY" @loadFromSerialized(serialized_squad) @current_squad.dirty = true @container.trigger 'xwing-backend:squadNameChanged' @container.trigger 'xwing-backend:squadDirtinessChanged' cb success: success error: error class Ship constructor: (args) -> # args @builder = args.builder @container = args.container # internal state @pilot = null @data = null # ship data @quickbuildId = -1 @linkedShip = null # some quickbuilds contain two ships, this variable may reference a Ship beeing part of the same quickbuild card @primary = true # only the primary ship of a linked ship pair will contribute points and serialization id @upgrades = [] @wingmates = [] # stores wingmates (quickbuild stuff only) @destroystate = null @setupUI() destroy: (cb) -> @resetPilot() @resetAddons() @teardownUI() idx = @builder.ships.indexOf this if idx < 0 throw new Error("Ship not registered with builder") @builder.ships.splice idx, 1 if @wingmates.length > 0 @setWingmates(0) else if @linkedShip != null @linkedShip.linkedShip = null if @linkedShip.wingmates?.length > 0 @linkedShip.removeFromWing(this) else await @builder.removeShip @linkedShip, defer() cb() copyFrom: (other) -> throw new Error("Cannot copy from self") if other is this #console.log "Attempt to copy #{other?.pilot?.name}" return unless other.pilot? and other.data? #console.log "Setting pilot to ID=#{other.pilot.id}" if @builder.isQuickbuild if not (other.pilot.unique or (other.pilot.max_per_squad? and @builder.countPilots(other.pilot.canonical_name) >= other.pilot.max_per_squad)) # check if any upgrades are unique. In that case the whole ship may not be copied no_uniques_involved = true for upgrade in other.upgrades if (upgrade.data?.unique? and upgrade.data.unique) or (upgrade.data?.max_per_squad? and @builder.countUpgrades(upgrade.data.canonical_name) >= upgrade.data.max_per_squad) or upgrade.data?.solitary? no_uniques_involved = false # select cheapest generic like above available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled) if available_pilots.length > 0 @setPilotById available_pilots[0].id, true break else return if no_uniques_involved @setPilotById other.quickbuildId else if other.pilot.unique or (other.pilot.max_per_squad? and @builder.countPilots(other.pilot.canonical_name) >= other.pilot.max_per_squad) # Look for cheapest generic or available unique, otherwise do nothing available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled) if available_pilots.length > 0 @setPilotById available_pilots[0].id, true else return else @setPilotById other.pilot.id, true # Can't just copy upgrades since slots may be different other_upgrades = {} for upgrade in other.upgrades if upgrade?.data? and not upgrade.data.unique and ((not upgrade.data.max_per_squad?) or @builder.countUpgrades(upgrade.data.canonical_name) < upgrade.data.max_per_squad) other_upgrades[upgrade.slot] ?= [] other_upgrades[upgrade.slot].push upgrade delayed_upgrades = {} for upgrade in @upgrades other_upgrade = (other_upgrades[upgrade.slot] ? []).shift() if other_upgrade? upgrade.setById other_upgrade.data.id if not upgrades.lastSetValid delayed_upgrades[other_upgrade.data.id] = upgrade for id, upgrade of delayed_upgrades upgrade.setById id @addStandardizedUpgrades() @updateSelections() @builder.container.trigger 'xwing:pointsUpdated' @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' setShipType: (ship_type) -> @pilot_selector.data('select2').container.show() if ship_type != @pilot?.ship if not @builder.isQuickbuild # Ship changed; select first non-unique pilot = (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not exportObj.pilotsById[result.id].unique)[0] if pilot # if there is a non-unique, use this one @setPilot pilot else # otherwise just set it to the first available pilot @setPilot (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when ((not exportObj.pilotsById[result.id].restriction_func? or exportObj.pilotsById[result.id].restriction_func(@)) and not (exportObj.pilotsById[result.id] in @builder.uniques_in_use.Pilot)))[0] else # get the first available pilot quickbuild_id = (result.id for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not result.disabled)[0] @setPilotById quickbuild_id @checkPilotSelectorQueryModal() # Clear ship background class for cls in @row.attr('class').split(/\s+/) if cls.indexOf('ship-') == 0 @row.removeClass cls # Show delete button @remove_button.fadeIn 'fast' @copy_button.fadeIn 'fast' @points_destroyed_button.fadeIn 'fast' # Ship background @row.addClass "ship-#{ship_type.toLowerCase().replace(/[^a-z0-9]/gi, '')}" @builder.container.trigger 'xwing:shipUpdated' setPilotById: (id, noautoequip = false) -> #sets pilot of this ship according to given id. Id might be pilotId or quickbuildId depending on mode. if not @builder.isQuickbuild @setPilot exportObj.pilotsById[parseInt id], noautoequip else if id != @quickbuildId @wingmate_selector.parent().hide() if @wingmates? and @wingmates.length > 0 # remove any wingmates, as the wing leader was just removed from the list @setWingmates(0) @linkedShip = null @quickbuildId = id @builder.current_squad.dirty = true @resetPilot() @resetAddons() if id? and id > -1 quickbuild = exportObj.quickbuildsById[parseInt id] new_pilot = exportObj.pilots[quickbuild.pilot] @data = exportObj.ships[quickbuild.ship] @builder.isUpdatingPoints = true # prevents unneccesary validations while still adding stuff if new_pilot?.unique? await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ] @pilot = new_pilot @setupAddons() if @pilot? @copy_button.show() @setShipType @pilot.ship # if this card contains more than one ship, make sure the other one is added as well if quickbuild.wingmate? && not @linkedShip? # try to join wingleader, if we have not been created by him for ship in @builder.ships if ship.quickbuildId == quickbuild.linkedId # found our leader. join him. ship.joinWing(this) @linkedShip = ship @primary = false @builder.isUpdatingPoints = false @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' return # we are done. if @linkedShip # we are already linked to some other ship if quickbuild.linkedId? # we will stay linked to another ship, so just set the linked one to an new pilot es well @linkedShip.setPilotById quickbuild.linkedId @linkedShip.primary = false unless quickbuild.wingmate? else # take care of associated ship if @linkedShip.wingmates?.length > 0 # we are no longer part of a wing @linkedShip.removeFromWing(this) else # we are no longer part of a linked pair, so the linked ship should be removed @linkedShip.linkedShip = null await @builder.removeShip @linkedShip, defer() @linkedShip = null else if quickbuild.linkedId? # we nare not already linked to another ship, but need one. Let's set one up @linkedShip = @builder.ships.slice(-1)[0] # during squad building there is an empty ship at the bottom, use that one and add a new empty one. # during squad loading there is no empty ship at the bottom, so we just create a new one and use it if @linkedShip.data != null @linkedShip = @builder.addShip() else @builder.addShip() @linkedShip.linkedShip = this @linkedShip.setPilotById quickbuild.linkedId # for pairs the first selected ship is master, so as we have been created first, we set the other ship to false # for wings the wingleader is always master, so we don't set the other ship to false, if we are just a wingmate @linkedShip.primary = false unless quickbuild.wingmate? @primary = !quickbuild.wingmate? if quickbuild?.wingleader? @wingmate_selector.parent().show() @wingmate_selector.val quickbuild.wingmates[0] @wingmate_selector.attr "min", quickbuild.wingmates[0] @wingmate_selector.attr "max", quickbuild.wingmates[quickbuild.wingmates.length - 1] @setWingmates quickbuild.wingmates[0] @builder.isUpdatingPoints = false @builder.container.trigger 'xwing:pointsUpdated' else @copy_button.hide() @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' addStandardizedUpgrades: -> idx = @builder.standard_list['Ship'].indexOf @data.name if idx > -1 for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, @builder.standard_list['Upgrade'][idx].slot) upgrade.setData @builder.standard_list['Upgrade'][idx] break setPilot: (new_pilot, noautoequip = false) -> # don't call this method directly, unless you know what you do. Use setPilotById for proper quickbuild handling if new_pilot != @pilot @builder.current_squad.dirty = true same_ship = @pilot? and new_pilot?.ship == @pilot.ship old_upgrades = {} if same_ship # track addons and try to reassign them for upgrade in @upgrades if upgrade?.data? old_upgrades[upgrade.slot] ?= [] old_upgrades[upgrade.slot].push upgrade @resetPilot() @resetAddons() if new_pilot? @data = exportObj.ships[new_pilot?.ship] if new_pilot?.unique? await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ] @pilot = new_pilot @setupAddons() if @pilot? @copy_button.show() @setShipType @pilot.ship @addStandardizedUpgrades() if (@pilot.autoequip? or (exportObj.ships[@pilot.ship].autoequip? and not same_ship)) and not noautoequip autoequip = (@pilot.autoequip ? []).concat(exportObj.ships[@pilot.ship].autoequip ? []) for upgrade_name in autoequip auto_equip_upgrade = exportObj.upgrades[upgrade_name] for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, auto_equip_upgrade.slot) upgrade.setData auto_equip_upgrade if same_ship delayed_upgrades = {} for upgrade in @upgrades old_upgrade = (old_upgrades[upgrade.slot] ? []).shift() if old_upgrade? upgrade.setById old_upgrade.data.id if not upgrade.lastSetValid delayed_upgrades[old_upgrade.data.id] = upgrade for id, upgrade of delayed_upgrades upgrade.setById id else @copy_button.hide() @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' resetPilot: -> if @pilot?.unique? await @builder.container.trigger 'xwing:releaseUnique', [ @pilot, 'Pilot', defer() ] @pilot = null setupAddons: -> if not @builder.isQuickbuild # Upgrades from pilot for slot in @pilot.slots ? [] @upgrades.push new exportObj.Upgrade ship: this container: @addon_container slot: slot else # Upgrades from quickbuild for upgrade_name in exportObj.quickbuildsById[@quickbuildId].upgrades ? [] upgrade_data = exportObj.upgrades[upgrade_name] if not upgrade_data? console.log("Unknown Upgrade: " + upgrade_name) continue upgrade = new exportObj.QuickbuildUpgrade ship: this container: @addon_container slot: upgrade_data.slot upgrade: upgrade_data upgrade.setData upgrade_data @upgrades.push upgrade resetAddons: -> await for upgrade in @upgrades upgrade.destroy defer() if upgrade? @upgrades = [] getPoints: -> if not @builder.isQuickbuild points = @pilot?.points ? 0 for upgrade in @upgrades points += upgrade.getPoints() @points_container.find('span').text points if points > 0 @points_container.fadeTo 'fast', 1 else @points_container.fadeTo 0, 0 points else quickbuild = exportObj.quickbuildsById[@quickbuildId] threat = if @primary then quickbuild?.threat ? 0 else 0 if quickbuild?.wingleader? threat = quickbuild.threat[quickbuild.wingmates.indexOf(@wingmates.length)] @points_container.find('span').text threat if threat > 0 @points_container.fadeTo 'fast', 1 else @points_container.fadeTo 0, 0 threat setWingmates: (wingmates) -> # creates/destroys wingmates to match number given as argument # todo: Check if number is valid for this quickbuild wing? if @wingmates?.length == wingmates # nothing to do, we already have correct number of wingmates. return if !@wingmates? || @wingmates.length == 0 # if no wingmates are set yet, use the linked buddy @wingmates = [@linkedShip] quickbuild = exportObj.quickbuildsById[@quickbuildId] while @wingmates.length < wingmates # create more wingmates newMate = @builder.ships.slice(-1)[0] # during squad building there is an empty ship at the bottom, use that one and add a new empty one. # during squad loading there is no empty ship at the bottom, so we just create a new one and use it if newMate.data != null newMate = @builder.addShip() else @builder.addShip() newMate.linkedShip = this # link new mate to us @wingmates.push(newMate) newMate.setPilotById quickbuild.linkedId # for pairs the first selected ship is master, so as we have been created first, we set the other ship to false # for wings the wingleader is always master, so we don't set the other ship to false, if we are just a wingmate newMate.primary = false @primary = true # he should not try to steal our primary position, as he is aware of beeing not squad leader, but in case he's not just set it. while @wingmates.length > wingmates # destroy wingmates dyingMate = @wingmates.pop() dyingMate.linkedShip = null # prevent the mate from killing us await @builder.removeShip dyingMate, defer() @wingmate_selector.val wingmates removeFromWing: (ship) -> # remove requested ship from wing @wingmates.removeItem(ship) # check if the wing is still valid, otherwise destroy it. quickbuild = exportObj.quickbuildsById[@quickbuildId] if !(@wingmates.length in quickbuild.wingmates) @destroy $.noop @wingmate_selector.val @wingmates.length joinWing: (ship) -> # remove requested ship from wing @wingmates.push(ship) # check if the wing is still valid, otherwise destroy the added ship quickbuild = exportObj.quickbuildsById[@quickbuildId] if !(@wingmates.length in quickbuild.wingmates) ship.destroy $.noop @removeFromWing(ship) @wingmate_selector.val @wingmates.length updateSelections: -> if @pilot? @ship_selector.select2 'data', id: @pilot.ship text: if exportObj.ships[@pilot.ship].display_name then exportObj.ships[@pilot.ship].display_name else @pilot.ship xws: exportObj.ships[@pilot.ship].xws icon: if exportObj.ships[@pilot.ship].icon then exportObj.ships[@pilot.ship].icon else exportObj.ships[@pilot.ship].xws @pilot_selector.select2 'data', id: @pilot.id text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then @pilot.skill + ' - ' else ''}#{if @pilot.display_name then @pilot.display_name else @pilot.name}#{if @quickbuildId != -1 then exportObj.quickbuildsById[@quickbuildId].suffix else ""} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})" @pilot_selector.data('select2').container.show() for upgrade in @upgrades points = upgrade.getPoints() upgrade.updateSelection points else @pilot_selector.select2 'data', null #@pilot_selector.data('select2').container.toggle(@ship_selector.val() != '') checkPilotSelectorQueryModal: -> if $(window).width() >= 768 @pilot_query_modal.hide() else if @pilot then @pilot_query_modal.show() setupUI: -> @row = $ document.createElement 'DIV' @row.addClass 'row ship mb-5 mb-sm-0' @row.insertBefore @builder.notes_container if @pilot? shipicon = if exportObj.ships[@pilot.ship].icon then exportObj.ships[@pilot.ship].icon else exportObj.ships[@pilot.ship].xws @row.append $.trim ''' <div class="col-md-3"> <div class="form-group d-flex"> <input class="ship-selector-container" type="hidden"></input> <div class="input-group-append"> <button class="btn btn-secondary d-block d-md-none ship-query-modal"><i class="fas fa-question"></i></button> </div> <br /> </div> <div class="form-group d-flex"> <input type="hidden" class="pilot-selector-container"></input> <div class="input-group-append"> <button class="btn btn-secondary pilot-query-modal"><i class="fas fa-question"></i></button> <br /> </div> </div> <label class="wingmate-label"> Wingmates: <input type="number" class="wingmate-selector"></input> </label> </div> <div class="col-md-1 points-display-container"> <span></span> </div> <div class="col-md-6 addon-container"> </div> <div class="col-md-2 button-container"> <button class="btn btn-danger remove-pilot side-button"><span class="d-none d-sm-block" data-toggle="tooltip" title="Remove Pilot"><i class="fa fa-times"></i></span><span class="d-block d-sm-none"> Remove Pilot</span></button> <button class="btn btn-light copy-pilot side-button"><span class="d-none d-sm-block" data-toggle="tooltip" title="Clone Pilot"><i class="far fa-copy"></i></span><span class="d-block d-sm-none"> Clone Pilot</span></button>&nbsp;&nbsp;&nbsp; <button class="btn btn-light points-destroyed side-button" points-state"><span class="destroyed-type" title="Points Destroyed"><i class="xwing-miniatures-font xwing-miniatures-font-title"></i></span></button> </div> ''' @row.find('.button-container span').tooltip() @ship_selector = $ @row.find('input.ship-selector-container') @pilot_selector = $ @row.find('input.pilot-selector-container') @wingmate_selector = $ @row.find('input.wingmate-selector') @ship_query_modal = $ @row.find('button.ship-query-modal') @pilot_query_modal = $ @row.find('button.pilot-query-modal') @ship_query_modal.click (e) => if @pilot @builder.showTooltip 'Ship', exportObj.ships[@pilot.ship], null, @builder.mobile_tooltip_modal, true @builder.mobile_tooltip_modal.modal 'show' @pilot_query_modal.click (e) => if @pilot @builder.showTooltip 'Pilot', @pilot, (@ if @pilot), @builder.mobile_tooltip_modal, true @builder.mobile_tooltip_modal.modal 'show' shipResultFormatter = (object, container, query) -> return """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.icon}"></i> #{object.text}""" shipSelectionFormatter = (object, container) -> return """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.icon}"></i> #{object.text}""" @ship_selector.select2 width: '100%' placeholder: exportObj.translate @builder.language, 'ui', 'shipSelectorPlaceholder' query: (query) => data = {results: []} data.results = @builder.getAvailableShipsMatching(query.term) query.callback(data) minimumResultsForSearch: if $.isMobile() then -1 else 0 formatResultCssClass: (obj) => if @builder.collection? and (@builder.collection.checks.collectioncheck == "true") not_in_collection = false if @pilot? and obj.id == exportObj.ships[@pilot.ship].id # Currently selected ship; mark as not in collection if it's neither # on the shelf nor on the table unless (@builder.collection.checkShelf('ship', obj.name) or @builder.collection.checkTable('pilot', obj.name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @builder.collection.checkShelf('ship', obj.name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' formatResult: shipResultFormatter formatSelection: shipResultFormatter @ship_selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @ship_selector.on 'change', (e) => @setShipType @ship_selector.val() @ship_selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' @builder.showTooltip 'Ship', exportObj.ships[select2_data.id] if select2_data?.id? @ship_selector.data('select2').container.on 'mouseover', (e) => @builder.showTooltip 'Ship', exportObj.ships[@pilot.ship] if @pilot @pilot_selector.select2 width: '100%' placeholder: exportObj.translate @builder.language, 'ui', 'pilotSelectorPlaceholder' query: (query) => data = {results: []} data.results = @builder.getAvailablePilotsForShipIncluding(@ship_selector.val(), (if not @builder.isQuickbuild then @pilot else @quickbuildId), query.term, true, @) query.callback(data) minimumResultsForSearch: if $.isMobile() then -1 else 0 formatResultCssClass: (obj) => if @builder.collection? and (@builder.collection.checks.collectioncheck == "true") not_in_collection = false name = "" if @builder.isQuickbuild name = exportObj.quickbuildsById[obj.id]?.pilot ? "unknown pilot" else name = obj.name if obj.id == @pilot?.id # Currently selected pilot; mark as not in collection if it's neither # on the shelf nor on the table unless (@builder.collection.checkShelf('pilot', name) or @builder.collection.checkTable('pilot', name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @builder.collection.checkShelf('pilot', name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' @pilot_selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @pilot_selector.on 'change', (e) => @setPilotById @pilot_selector.select2('val') @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' @builder.backend_status.fadeOut 'slow' @pilot_selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' if @builder.isQuickbuild @builder.showTooltip 'Quickbuild', exportObj.quickbuildsById[select2_data.id], {ship: @data?.name} if select2_data?.id? else @builder.showTooltip 'Pilot', exportObj.pilotsById[select2_data.id] if select2_data?.id? @pilot_selector.data('select2').container.on 'mouseover', (e) => @builder.showTooltip 'Pilot', @pilot, @ if @pilot @pilot_selector.data('select2').container.hide() if @builder.isQuickbuild @wingmate_selector.on 'change', (e) => @setWingmates parseInt @wingmate_selector.val() @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' @builder.backend_status.fadeOut 'slow' @wingmate_selector.on 'mousemove-filtered', (e) => return # TODO: show tooltip of wingmate # select2_data = $(e.target).closest('.select2-result').data 'select2-data' # if @builder.isQuickbuild # @builder.showTooltip 'Quickbuild', exportObj.quickbuildsById[select2_data.id], {ship: @data?.name} if select2_data?.id? # else # @builder.showTooltip 'Pilot', exportObj.wingmatesById[select2_data.id] if select2_data?.id? # @wingmate_selector.on 'mouseover', (e) => # @builder.showTooltip 'Pilot', @wingmate, @ if @wingmate # @wingmate_selector.parent().hide() @points_container = $ @row.find('.points-display-container') @points_container.fadeTo 0, 0 @addon_container = $ @row.find('div.addon-container') @remove_button = $ @row.find('button.remove-pilot') @remove_button.click (e) => e.preventDefault() @row.slideUp 'fast', () => @builder.removeShip this @backend_status?.fadeOut 'slow' @remove_button.hide() @copy_button = $ @row.find('button.copy-pilot') @copy_button.click (e) => clone = @builder.ships[@builder.ships.length - 1] clone.copyFrom(this) @copy_button.hide() @checkPilotSelectorQueryModal() @points_destroyed_button_span = $ @row.find('.destroyed-type') @points_destroyed_button = $ @row.find('button.points-destroyed') @points_destroyed_button.click (e) => if @destroystate == 1 @destroystate = 2 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-crit"></i>' else if @destroystate == 2 @destroystate = 0 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-title"></i>' else @destroystate = 1 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-hit"></i>' @builder.onPointsUpdated() @points_destroyed_button.hide() teardownUI: -> @row.text '' @row.remove() toString: -> if @pilot? "Pilot #{if @pilot.display_name then @pilot.display_name else @pilot.name} flying #{if @data.display_name then @data.display_name else @data.name}" else "Ship without pilot" toHTML: -> effective_stats = @effectiveStats() action_bar = @builder.formatActions(effective_stats.actions,"&nbsp;&nbsp;", @pilot.keyword ? []) attack_icon = @data.attack_icon ? 'xwing-miniatures-font-frontarc' engagementHTML = if (@pilot.engagement?) then $.trim """ <span class="info-data info-skill">ENG #{@pilot.engagement}</span> """ else '' attackHTML = if (effective_stats.attack?) then $.trim """ <i class="xwing-miniatures-font header-attack #{attack_icon}"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attack ? @data.attack), effective_stats, 'attack')}</span> """ else '' if effective_stats.attackbull? attackbullHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackbull ? @data.attackbull), effective_stats, 'attackbull')}</span>""" else attackbullHTML = '' if effective_stats.attackb? attackbHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackb ? @data.attackb), effective_stats, 'attackb')}</span>""" else attackbHTML = '' if effective_stats.attackf? attackfHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackf ? @data.attackf), effective_stats, 'attackf')}</span>""" else attackfHTML = '' if effective_stats.attackt? attacktHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackt ? @data.attackt), effective_stats, 'attackt')}</span>""" else attacktHTML = '' if effective_stats.attackl? attacklHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-leftarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackl ? @data.attackl), effective_stats, 'attackl')}</span>""" else attacklHTML = '' if effective_stats.attackr? attackrHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-rightarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackr ? @data.attackr), effective_stats, 'attackr')}</span>""" else attackrHTML = '' if effective_stats.attackdt? attackdtHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackdt ? @data.attackdt), effective_stats, 'attackdt')}</span>""" else attackdtHTML = '' recurringicon = '' if @data.energyrecurr? count = 0 while count < @data.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count energyHTML = if (@pilot.ship_override?.energy? or @data.energy?) then $.trim """ <i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i> <span class="info-data info-energy">#{statAndEffectiveStat((@pilot.ship_override?.energy ? @data.energy), effective_stats, 'energy')}#{recurringicon}</span> """ else '' forceHTML = if (@pilot.force?) then $.trim """ <i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i> <span class="info-data info-force">#{statAndEffectiveStat((@pilot.ship_override?.force ? @pilot.force), effective_stats, 'force')}<sup><i class="fas fa-caret-up"></i></sup></span> """ else '' if @pilot.charge? recurringicon = '' if @pilot.recurring? if @pilot.recurring > 0 count = 0 while count < @pilot.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = @pilot.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """<i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i><span class="info-data info-charge">#{statAndEffectiveStat((@pilot.ship_override?.charge ? @pilot.charge), effective_stats, 'charge')}#{recurringicon}</span>""" else chargeHTML = '' shieldRECUR = '' if @data.shieldrecurr? count = 0 while count < @data.shieldrecurr shieldRECUR += """<sup><i class="fas fa-caret-up"></i></sup>""" ++count shieldIconHTML = '' if effective_stats.shields for _ in [effective_stats.shields..2] by -1 shieldIconHTML += """<i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield expanded-hull-or-shield"></i>""" shieldIconHTML += """<i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i>""" hullIconHTML = '' if effective_stats.hull for _ in [effective_stats.hull..2] by -1 hullIconHTML += """<i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull expanded-hull-or-shield"></i>""" hullIconHTML += """<i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i>""" html = $.trim """ <div class="fancy-pilot-header"> <div class="pilot-header-text">#{if @pilot.display_name then @pilot.display_name else @pilot.name} <i class="xwing-miniatures-ship xwing-miniatures-ship-#{@data.xws}"></i><span class="fancy-ship-type"> #{if @data.display_name then @data.display_name else @data.name}</span></div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle pilot-points">#{if @quickbuildId != -1 then (if @primary then @getPoints() else '*') else @pilot.points}</div> </div> </div> </div> <div class="fancy-pilot-stats"> <div class="pilot-stats-content"> <span class="info-data info-skill">INI #{statAndEffectiveStat(@pilot.skill, effective_stats, 'skill')}</span> #{engagementHTML} #{attackbullHTML} #{attackHTML} #{attackbHTML} #{attackfHTML} #{attacktHTML} #{attacklHTML} #{attackrHTML} #{attackdtHTML} <i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i> <span class="info-data info-agility">#{statAndEffectiveStat((@pilot.ship_override?.agility ? @data.agility), effective_stats, 'agility')}</span> #{hullIconHTML} <span class="info-data info-hull">#{statAndEffectiveStat((@pilot.ship_override?.hull ? @data.hull), effective_stats, 'hull')}</span> #{shieldIconHTML} <span class="info-data info-shields">#{statAndEffectiveStat((@pilot.ship_override?.shields ? @data.shields), effective_stats, 'shields')}#{shieldRECUR}</span> #{energyHTML} #{forceHTML} #{chargeHTML} <br /> #{action_bar} </div> </div> """ # Maneuver Dials have been moved at the bottom of the squad, rather than beeing added to each ship # dialHTML = @builder.getManeuverTableHTML(effective_stats.maneuvers, @data.maneuvers) # # html += $.trim """ # <div class="fancy-dial"> # #{dialHTML} # </div> # """ if @pilot.text html += $.trim """ <div class="fancy-pilot-text">#{@pilot.text}</div> """ slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 html += $.trim """ <div class="fancy-upgrade-container"> """ for upgrade in slotted_upgrades points = upgrade.getPoints() html += upgrade.toHTML points html += $.trim """ </div> """ HalfPoints = Math.ceil @getPoints() / 2 Threshold = Math.ceil (effective_stats['hull'] + effective_stats['shields']) / 2 html += $.trim """ <div class="ship-points-total"> <strong>Ship Total: #{@getPoints()}, Half Points: #{HalfPoints}, Threshold: #{Threshold}</strong> </div> """ """<div class="fancy-ship">#{html}</div>""" toTableRow: -> table_html = $.trim """ <tr class="simple-pilot"> <td class="name">#{if @pilot.display_name then @pilot.display_name else @pilot.name} &mdash; #{if @data.display_name then @data.display_name else @data.name}</td> <td class="points">#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points}</td> </tr> """ slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades points = upgrade.getPoints() table_html += upgrade.toTableRow points # if @getPoints() != @pilot.points table_html += """<tr class="simple-ship-total"><td colspan="2">Ship Total: #{@getPoints()}</td></tr>""" halfPoints = Math.ceil @getPoints() / 2 threshold = Math.ceil (@effectiveStats()['hull'] + @effectiveStats()['shields']) / 2 table_html += """<tr class="simple-ship-half-points"><td colspan="2">Half Points: #{halfPoints} Threshold: #{threshold}</td></tr>""" table_html += '<tr><td>&nbsp;</td><td></td></tr>' table_html toSimpleCopy: -> simplecopy = """#{@pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points}) \n""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 simplecopy +=" " simplecopy_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_simplecopy = upgrade.toSimpleCopy points simplecopy_upgrades.push upgrade_simplecopy if upgrade_simplecopy? simplecopy += simplecopy_upgrades.join " " simplecopy += """ \n""" halfPoints = Math.ceil @getPoints() / 2 threshold = Math.ceil (@effectiveStats()['hull'] + @effectiveStats()['shields']) / 2 simplecopy += """Ship total: #{@getPoints()} Half Points: #{halfPoints} Threshold: #{threshold} \n \n""" simplecopy toRedditText: -> reddit = """**#{@pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})** \n""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 reddit +=" " reddit_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_reddit = upgrade.toRedditText points reddit_upgrades.push upgrade_reddit if upgrade_reddit? reddit += reddit_upgrades.join " " reddit += """&nbsp;*Ship total: (#{@getPoints()})* \n""" reddit toTTSText: -> tts = """#{exportObj.toTTS(@pilot.name)}""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades upgrade_tts = upgrade.toTTSText() tts += (" + " + upgrade_tts) if upgrade_tts? tts += " / " toBBCode: -> bbcode = """[b]#{if @pilot.display_name then @pilot.display_name else @pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})[/b]""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 bbcode +="\n" bbcode_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_bbcode = upgrade.toBBCode points bbcode_upgrades.push upgrade_bbcode if upgrade_bbcode? bbcode += bbcode_upgrades.join "\n" bbcode toSimpleHTML: -> html = """<b>#{if @pilot.display_name then @pilot.display_name else @pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})</b><br />""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_html = upgrade.toSimpleHTML points html += upgrade_html if upgrade_html? html toSerialized: -> # PILOT_ID:UPGRADEID1,UPGRADEID2:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2 if @builder.isQuickbuild if (!@wingmates? || @wingmates.length == 0) then """#{@quickbuildId}X""" else """#{@quickbuildId}X#{@wingmates.length}""" else upgrades = """#{upgrade?.data?.id ? "" for upgrade, i in @upgrades}""".replace(/,/g, "W") [ @pilot.id, upgrades, ].join 'X' fromSerialized: (version, serialized) -> # adds a ship from the given serialized data to the squad. # returns true, if all upgrades have been added successfully, false otherwise # returning false does not necessary mean nothing has been added, but some stuff might have been dropped (e.g. 0-0-0 if vader is not yet in the squad) everythingadded = true switch version # version 1-3 are 1st edition x-wing only, so we may as well delete them. # version 4 was the final version of 1st edition, and the first few weeks of 2nd edition. # version 5 is the current version. It handles titles and mods as regular upgrades. when 4, 5, 6 # PILOT_ID:UPGRADEID1,UPGRADEID2:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2 # conferredaddons are upgrade slots added by e.g. titles # version 5 is the same as version 4, but title and mod has been dropped (as they are treated as upgrades anyways). Thus, we may differ by length if (serialized.split ':').length == 3 # version 5,6 [ pilot_id, upgrade_ids, conferredaddon_pairs ] = serialized.split ':' else # version 4 [ pilot_id, upgrade_ids, version_4_compatibility_placeholder_title, version_4_compatibility_placeholder_mod, conferredaddon_pairs ] = serialized.split ':' @setPilotById parseInt(pilot_id), true # make sure the pilot is valid return false unless @validate deferred_ids = [] for upgrade_id, i in upgrade_ids.split ',' upgrade_id = parseInt upgrade_id continue if upgrade_id < 0 or isNaN(upgrade_id) # Defer fat upgrades if @upgrades[i].isOccupied() or @upgrades[i].dataById[upgrade_id]?.also_occupies_upgrades? deferred_ids.push upgrade_id else @upgrades[i].setById upgrade_id everythingadded &= @upgrades[i].lastSetValid for deferred_id in deferred_ids deferred_id_added = false for upgrade, i in @upgrades if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot continue upgrade.setById deferred_id deferred_id_added = upgrade.lastSetValid break everythingadded &= deferred_id_added if conferredaddon_pairs? conferredaddon_pairs = conferredaddon_pairs.split ',' else conferredaddon_pairs = [] for upgrade in @upgrades if upgrade?.data? and upgrade.conferredAddons.length > 0 upgrade_conferred_addon_pairs = conferredaddon_pairs.splice 0, upgrade.conferredAddons.length for conferredaddon_pair, i in upgrade_conferred_addon_pairs [ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.' addon_id = parseInt addon_id addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized] if not addon_cls console.log("Something went wrong... could not serialize properly") continue conferred_addon = upgrade.conferredAddons[i] if conferred_addon instanceof addon_cls conferred_addon.setById addon_id everythingadded &= conferred_addon.lastSetValid else throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there") when 7, 8 pilot_splitter = if version > 7 then 'X' else ':' upgrade_splitter = if version > 7 then 'W' else ',' # version 7 is an further extension of version 6, allowing arbitrary order of upgrades. It currently ignores conferredaddons (upgrades in slots added by titles etc), probably we can drop the special case handling for them and include them into the usual upgrade list? [ pilot_id, upgrade_ids, conferredaddon_pairs ] = serialized.split pilot_splitter upgrade_ids = upgrade_ids.split upgrade_splitter # set the pilot @setPilotById parseInt(pilot_id), true # make sure the pilot is valid return false unless @validate if !@builder.isQuickbuild # iterate over upgrades to be added, and remove all that have been successfully added for _ in [1 ... 3] # try adding each upgrade a few times, as the required slots might be added in by titles etc and are not yet available on the first try for i in [upgrade_ids.length - 1 ... -1] upgrade_id = upgrade_ids[i] upgrade = exportObj.upgradesById[upgrade_id] if not upgrade? upgrade_ids.splice(i,1) # Remove unknown or empty ID if upgrade_id != "" console.log("Unknown upgrade id " + upgrade_id + " could not be added. Please report that error") everythingadded = false continue for upgrade_selection in @upgrades if exportObj.slotsMatching(upgrade.slot, upgrade_selection.slot) and not upgrade_selection.isOccupied() upgrade_selection.setById upgrade_id if upgrade_selection.lastSetValid upgrade_ids.splice(i,1) # added successfully, remove from list break else # we are in quickbuild. Number of wingmates might be provided as upgrade ID of a quickbuild if upgrade_ids.length > 0 && @wingmates.length > 0 # check if we are actually a wingleader @setWingmates(upgrade_ids[0]) everythingadded &= upgrade_ids.length == 0 @updateSelections() everythingadded effectiveStats: -> stats = attack: @pilot.ship_override?.attack ? @data.attack attackf: @pilot.ship_override?.attackf ? @data.attackf attackbull: @pilot.ship_override?.attackbull ? @data.attackbull attackb: @pilot.ship_override?.attackb ? @data.attackb attackt: @pilot.ship_override?.attackt ? @data.attackt attackl: @pilot.ship_override?.attackl ? @data.attackl attackr: @pilot.ship_override?.attackr ? @data.attackr attackdt: @pilot.ship_override?.attackdt ? @data.attackdt energy: @pilot.ship_override?.energy ? @data.energy agility: @pilot.ship_override?.agility ? @data.agility hull: @pilot.ship_override?.hull ? @data.hull shields: @pilot.ship_override?.shields ? @data.shields force: (@pilot.ship_override?.force ? @pilot.force) ? 0 charge: @pilot.ship_override?.charge ? @pilot.charge actions: (@pilot.ship_override?.actions ? @data.actions).slice 0 # need a deep copy of maneuvers array stats.maneuvers = [] for s in [0 ... (@data.maneuvers ? []).length] stats.maneuvers[s] = @data.maneuvers[s].slice 0 # Droid conversion of Focus to Calculate if @pilot.keyword? and ("Droid" in @pilot.keyword) and stats.actions? new_stats = [] for statentry in stats.actions new_stats.push statentry.replace("Focus","Calculate") stats.actions = new_stats for upgrade in @upgrades upgrade.data.modifier_func(stats) if upgrade?.data?.modifier_func? @pilot.modifier_func(stats) if @pilot?.modifier_func? stats validate: -> # Remove addons that violate their validation functions (if any) one by one # until everything checks out # If there is no explicit validation_func, use restriction_func # Returns true, if nothing has been changed, and false otherwise # check if we are an empty selection, which is always valid if not @pilot? return true unchanged = true max_checks = 32 # that's a lot of addons if @builder.isEpic #Command Epic adding if not ("Command" in @pilot.slots) addCommand = true for upgrade in @upgrades if ("Command" == upgrade.slot) and (this == upgrade.ship) addCommand = false if addCommand == true @upgrades.push new exportObj.Upgrade ship: this container: @addon_container slot: "Command" else if !@builder.isQuickbuild #cleanup Command upgrades for i in [@upgrades.length - 1 ... -1] upgrade = @upgrades[i] if upgrade.slot == "Command" upgrade.destroy $.noop @upgrades.splice i,1 for i in [0...max_checks] valid = true pilot_func = @pilot?.validation_func ? @pilot?.restriction_func ? undefined if (pilot_func? and not pilot_func(this, @pilot)) or not (@builder.isItemAvailable(@pilot, true)) # we go ahead and happily remove ourself. Of course, when calling a method like validate on an object, you have to expect that it will dissappear, right? @builder.removeShip this return false # no need to check anything further, as we do not exist anymore # everything is limited in X-Wing 2.0, so we need to check if any upgrade is equipped more than once equipped_upgrades = [] for upgrade in @upgrades func = upgrade?.data?.validation_func ? undefined if func? func_result = upgrade?.data?.validation_func(this, upgrade) else if upgrade?.data?.restrictions func_result = @restriction_check(upgrade.data.restrictions, upgrade) # check if either a) validation func not met or b) upgrade already equipped (in 2.0 everything is limited) or c) upgrade is not available (e.g. not Hyperspace legal) # ignore those checks if this is a quickbuild squad, as quickbuild does whatever it wants to do... if ((func_result? and not func_result) or (upgrade?.data? and (upgrade.data in equipped_upgrades or (upgrade.data.faction? and not @builder.isOurFaction(upgrade.data.faction,@pilot.faction)) or not @builder.isItemAvailable(upgrade.data)))) and not @builder.isQuickbuild #console.log "Invalid upgrade: #{upgrade?.data?.name}" upgrade.setById null valid = false unchanged = false break if upgrade?.data? and upgrade.data equipped_upgrades.push(upgrade?.data) break if valid @updateSelections() unchanged checkUnreleasedContent: -> if @pilot? and not exportObj.isReleased @pilot #console.log "#{@pilot.name} is unreleased" return true for upgrade in @upgrades if upgrade?.data? and not exportObj.isReleased upgrade.data #console.log "#{upgrade.data.id} is unreleased" return true false hasAnotherUnoccupiedSlotLike: (upgrade_obj, upgradeslot) -> for upgrade in @upgrades continue if upgrade == upgrade_obj or upgrade.slot != upgradeslot return true unless upgrade.isOccupied() false restriction_check: (restrictions, upgrade_obj) -> effective_stats = @effectiveStats() for r in restrictions if r[0] == "orUnique" if @checkListForUnique(r[1].toLowerCase().replace(/[^0-9a-z]/gi, '').replace(/\s+/g, '-')) return true switch r[0] when "Base" switch r[1] when "Small" if @data.medium? or @data.large? or @data.huge? then return false when "Small or Medium" if @data.large? or @data.huge? then return false when "Medium" if not (@data.medium?) then return false when "Medium or Large" if not (@data.medium? or @data.large?) then return false when "Large" if not (@data.large?) then return false when "Huge" if not (@data.huge?) then return false when "Standard" if @data.huge? then return false when "Action" if not ((r[1] in effective_stats.actions) or ("*#{r[1]}" in effective_stats.actions) or ("F-#{r[1]}" in effective_stats.actions) or ("R-#{r[1]}" in effective_stats.actions)) then return false when "Keyword" if not (@checkKeyword(r[1])) then return false when "Equipped" if not ((@doesSlotExist(r[1]) and not @hasAnotherUnoccupiedSlotLike(upgrade_obj, r[1]))) then return false when "Slot" if not @hasAnotherUnoccupiedSlotLike(upgrade_obj, r[1]) then return false when "AttackArc" if not @data.attackb? then return false when "ShieldsGreaterThan" if not (@data.shields > r[1]) then return false when "EnergyGreatterThan" if not (effective_stats.energy > r[1]) then return false when "InitiativeGreaterThan" if not (@pilot.skill > r[1]) then return false when "InitiativeLessThan" if not (@pilot.skill < r[1]) then return false when "AgilityEquals" if not (effective_stats.agility == r[1]) then return false when "isUnique" if r[1] != @pilot.unique? then return false when "Format" switch r[1] when "Epic" if not (@data.name in exportObj.epicExclusionsList) then return false when "Standard" if @data.name in exportObj.epicExclusionsList then return false when "Faction" if @pilot.faction != r[1] then return false return true doesSlotExist: (slot) -> for upgrade in @upgrades if slot == upgrade.slot return true false isSlotOccupied: (slot_name) -> for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, slot_name) return true unless upgrade.isOccupied() false checkKeyword: (keyword) -> if @data.name?.includes(keyword) return true for words in @data.keyword ? [] if words == keyword return true for words in @pilot.keyword ? [] if words == keyword return true for upgrade in @upgrades for word in upgrade?.data?.keyword ? [] if word == keyword return true false checkListForUnique: (name) -> for t, things of @builder.uniques_in_use if t != 'Slot' return true if name in (thing.canonical_name.getXWSBaseName() for thing in things) false toXWS: -> xws = id: (@pilot.xws ? @pilot.canonical_name) name: (@pilot.xws ? @pilot.canonical_name) # name is no longer part of xws 2.0.0, and was replaced by id. However, we will add it here for some kind of backward compatibility. May be removed, as soon as everybody is using id. points: @getPoints() #ship: @data.canonical_name ship: @data.xws.canonicalize() if @data.multisection xws.multisection = @data.multisection.slice 0 upgrade_obj = {} for upgrade in @upgrades if upgrade?.data? upgrade.toXWS upgrade_obj if Object.keys(upgrade_obj).length > 0 xws.upgrades = upgrade_obj xws getConditions: -> if Set? conditions = new Set() if @pilot?.applies_condition? if @pilot.applies_condition instanceof Array for condition in @pilot.applies_condition conditions.add(exportObj.conditionsByCanonicalName[condition]) else conditions.add(exportObj.conditionsByCanonicalName[@pilot.applies_condition]) for upgrade in @upgrades if upgrade?.data?.applies_condition? if upgrade.data.applies_condition instanceof Array for condition in upgrade.data.applies_condition conditions.add(exportObj.conditionsByCanonicalName[condition]) else conditions.add(exportObj.conditionsByCanonicalName[upgrade.data.applies_condition]) conditions else console.warn 'Set not supported in this JS implementation, not implementing conditions' [] class GenericAddon constructor: (args) -> # args @ship = args.ship @container = $ args.container # internal state @data = null @unadjusted_data = null @conferredAddons = [] @serialization_code = 'X' @occupied_by = null @occupying = [] @destroyed = false # Overridden by children @type = null @dataByName = null @dataById = null @adjustment_func = args.adjustment_func if args.adjustment_func? @filter_func = args.filter_func if args.filter_func? @placeholderMod_func = if args.placeholderMod_func? then args.placeholderMod_func else (x) => x destroy: (cb, args...) -> return cb(args) if @destroyed if @data?.unique? await @ship.builder.container.trigger 'xwing:releaseUnique', [ @data, @type, defer() ] if @data?.standardized? @removeStandardized() @destroyed = true @rescindAddons() @deoccupyOtherUpgrades() @selector.select2 'destroy' @selectorwrap.remove() cb args setupSelector: (args) -> @selectorwrap = $ document.createElement 'div' @selectorwrap.addClass 'form-group d-flex upgrade-box' @selector = $ document.createElement 'INPUT' @selector.attr 'type', 'hidden' @selectorwrap.append @selector @selectorwrap.append $.trim ''' <div class="input-group-addon"> <button class="btn btn-secondary d-block d-md-none upgrade-query-modal"><i class="fas fa-question"></i></button> </div> ''' @upgrade_query_modal = $ @selectorwrap.find('button.upgrade-query-modal') @container.append @selectorwrap args.minimumResultsForSearch = -1 if $.isMobile() args.formatResultCssClass = (obj) => if @ship.builder.collection? not_in_collection = false if obj.id == @data?.id # Currently selected card; mark as not in collection if it's neither # on the shelf nor on the table unless (@ship.builder.collection.checkShelf(@type.toLowerCase(), obj.name) or @ship.builder.collection.checkTable(@type.toLowerCase(), obj.name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @ship.builder.collection.checkShelf(@type.toLowerCase(), obj.name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' args.formatSelection = (obj, container) => icon = switch @type when 'Upgrade' @slot.toLowerCase().replace(/[^0-9a-z]/gi, '') else @type.toLowerCase().replace(/[^0-9a-z]/gi, '') icon = icon.replace("configuration", "config") .replace("force", "forcepower") # Append directly so we don't have to disable markup escaping $(container).append """<i class="xwing-miniatures-font xwing-miniatures-font-#{icon}"></i> #{obj.text}""" # If you return a string, Select2 will render it undefined @selector.select2 args @upgrade_query_modal.click (e) => if @data console.log "#{@data.name}" @ship.builder.showTooltip 'Addon', @data, ({addon_type: @type} if @data?) , @ship.builder.mobile_tooltip_modal, true @ship.builder.mobile_tooltip_modal.modal 'show' @selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @selector.on 'change', (e) => @setById @selector.select2('val') @ship.builder.current_squad.dirty = true @ship.builder.container.trigger 'xwing-backend:squadDirtinessChanged' @ship.builder.backend_status.fadeOut 'slow' @selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' @ship.builder.showTooltip 'Addon', @dataById[select2_data.id], {addon_type: @type} if select2_data?.id? @selector.data('select2').container.on 'mouseover', (e) => @ship.builder.showTooltip 'Addon', @data, {addon_type: @type} if @data? setById: (id) -> @setData @dataById[parseInt id] setByName: (name) -> @setData @dataByName[$.trim name] setData: (new_data) -> if new_data?.id != @data?.id if @data?.unique? or @data?.solitary? await @ship.builder.container.trigger 'xwing:releaseUnique', [ @unadjusted_data, @type, defer() ] if @data?.standardized? @removeStandardized() @rescindAddons() @deoccupyOtherUpgrades() if new_data?.unique? or new_data?.solitary? try await @ship.builder.container.trigger 'xwing:claimUnique', [ new_data, @type, defer() ] catch alreadyClaimed @ship.builder.container.trigger 'xwing:pointsUpdated' @lastSetValid = false return # Need to make a copy of the data, but that means I can't just check equality @data = @unadjusted_data = new_data if @data? if @data.superseded_by_id return @setById @data.superseded_by_id if @adjustment_func? @data = @adjustment_func(@data) @unequipOtherUpgrades() @occupyOtherUpgrades() @conferAddons() if @data.standardized? @addToStandardizedList() else @deoccupyOtherUpgrades() # this will remove not allowed upgrades (is also done on pointsUpdated). We do it explicitly so we can tell if the setData was successfull @lastSetValid = @ship.validate() @ship.builder.container.trigger 'xwing:pointsUpdated' addToStandardizedList: -> # check first if standard combo exists and return if it does idx = @ship.builder.standard_list['Ship'].indexOf @ship.data.name if idx > -1 if @ship.builder.standard_list['Upgrade'][idx]?.name == @data.name return @ship.builder.standard_list['Upgrade'].push @data @ship.builder.standard_list['Ship'].push @ship.data.name removeStandardized: -> # removes the ship upgrade combo from the stanard list array idx = @ship.builder.standard_list['Ship'].indexOf @ship.data.name if idx > -1 if @ship.builder.standard_list['Upgrade'][idx]?.name == @data.name @ship.builder.standard_list['Upgrade'].splice idx,1 @ship.builder.standard_list['Ship'].splice idx,1 # now remove all upgrades of the same name nameToRemove = @data.name for ship in @ship.builder.ships if ship.data?.name == @ship.data.name for upgrade in ship.upgrades if upgrade.data?.name == nameToRemove upgrade.data = null conferAddons: -> if @data.confersAddons? and !@ship.builder.isQuickbuild and @data.confersAddons.length > 0 for addon in @data.confersAddons cls = addon.type args = ship: @ship container: @container args.slot = addon.slot if addon.slot? args.adjustment_func = addon.adjustment_func if addon.adjustment_func? args.filter_func = addon.filter_func if addon.filter_func? args.auto_equip = addon.auto_equip if addon.auto_equip? args.placeholderMod_func = addon.placeholderMod_func if addon.placeholderMod_func? addon = new cls args if addon instanceof exportObj.Upgrade @ship.upgrades.push addon else throw new Error("Unexpected addon type for addon #{addon}") @conferredAddons.push addon rescindAddons: -> await for addon in @conferredAddons addon.destroy defer() for addon in @conferredAddons if addon instanceof exportObj.Upgrade @ship.upgrades.removeItem addon else throw new Error("Unexpected addon type for addon #{addon}") @conferredAddons = [] getPoints: (data = @data, ship = @ship) -> # Moar special case jankiness if data?.variableagility? data?.pointsarray[ship.data.agility] else if data?.variablebase? if ship?.data.medium? data?.pointsarray[1] else if ship?.data.large? data?.pointsarray[2] else if ship?.data.huge? data?.pointsarray[3] else data?.pointsarray[0] else if data?.variableinit? data?.pointsarray[ship.pilot.skill] else data?.points ? 0 updateSelection: (points) -> if @data? @selector.select2 'data', id: @data.id text: "#{if @data.display_name then @data.display_name else @data.name} (#{points}#{if @data.pointsarray then '*' else ''})" else @selector.select2 'data', null toString: -> if @data? "#{if @data.display_name then @data.display_name else @data.name} (#{@getPoints()})" else "No #{@type}" toHTML: (points) -> if @data? if @data.slot? and @data.slot == "HardpointShip" upgrade_slot_font = "hardpoint" else upgrade_slot_font = (@data.slot ? @type).toLowerCase().replace(/[^0-9a-z]/gi, '') match_array = @data.text?match(/(<span.*<\/span>)<br \/><br \/>(.*)/) if match_array restriction_html = '<div class="card-restriction-container">' + match_array[1] + '</div>' text_str = match_array[2] else restriction_html = '' text_str = @data.text attackHTML = "" if @data.range? attackrangebonus = if (@data.rangebonus?) then """<span class="upgrade-attack-rangebonus"><i class="xwing-miniatures-font xwing-miniatures-font-rangebonusindicator"></i></span>""" else '' attackStats = $.trim """ <span class="upgrade-attack-range">#{@data.range}</span> #{attackrangebonus} """ attackIcon = if (@data.attack?) then $.trim """ <span class="info-data info-attack">#{@data.attack}</span> <i class="xwing-miniatures-font xwing-miniatures-font-frontarc"></i> """ else if (@data.attackt?) then $.trim """ <span class="info-data info-attack">#{@data.attackt}</span> <i class="xwing-miniatures-font xwing-miniatures-font-singleturretarc"></i> """ else if (@data.attackdt?) then $.trim """ <span class="info-data info-attack">#{@data.attackdt}</span> <i class="xwing-miniatures-font xwing-miniatures-font-doubleturretarc"></i> """ else if (@data.attackl?) then $.trim """ <span class="info-data info-attack">#{@data.attackl}</span> <i class="xwing-miniatures-font xwing-miniatures-font-leftarc"></i> """ else if (@data.attackr?) then $.trim """ <span class="info-data info-attack">#{@data.attackr}</span> <i class="xwing-miniatures-font xwing-miniatures-font-rightarc"></i> """ else if (@data.attackbull?) then $.trim """ <span class="info-data info-attack">#{@data.attackbull}</span> <i class="xwing-miniatures-font xwing-miniatures-font-bullseyearc"></i> """ else '' attackHTML = $.trim """ <div class="upgrade-attack"> #{attackStats} #{attackIcon} </div> """ if @data.charge? recurringicon = '' if @data.recurring? if @data.recurring > 0 count = 0 while count < @data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = @data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """ <div class="upgrade-charge"> <span class="info-data info-charge">#{@data.charge}</span> <i class="xwing-miniatures-font xwing-miniatures-font-charge"></i>#{recurringicon} </div> """ else chargeHTML = $.trim '' if (@data.force?) forceHTML = $.trim """ <div class="upgrade-force"> <span class="info-data info-force">#{@data.force}</span> <i class="xwing-miniatures-font xwing-miniatures-font-forcecharge"></i><sup><i class="fas fa-caret-up"></i></sup> </div> """ else forceHTML = $.trim '' $.trim """ <div class="upgrade-container"> <div class="upgrade-stats"> <div class="upgrade-name"><i class="xwing-miniatures-font xwing-miniatures-font-#{upgrade_slot_font}"></i>#{if @data.display_name then @data.display_name else @data.name}</div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle upgrade-points">#{points}</div> </div> </div> #{restriction_html} </div> #{attackHTML} #{chargeHTML} #{forceHTML} <div class="upgrade-text">#{text_str}</div> <div style="clear: both;"></div> </div> """ else '' toTableRow: (points) -> if @data? $.trim """ <tr class="simple-addon"> <td class="name">#{if @data.display_name then @data.display_name else @data.name}</td> <td class="points">#{points}</td> </tr> """ else '' toSimpleCopy: (points) -> if @data? """#{@data.name} (#{points}) \n""" else null toRedditText: (points) -> if @data? """*&nbsp;#{@data.name} (#{points})* \n""" else null toTTSText: () -> if @data? """#{exportObj.toTTS(@data.name)}""" else null toBBCode: (points) -> if @data? """[i]#{if @data.display_name then @data.display_name else @data.name} (#{points})[/i]""" else null toSimpleHTML: (points) -> if @data? """<i>#{if @data.display_name then @data.display_name else @data.name} (#{points})</i><br />""" else '' toSerialized: -> """#{@serialization_code}.#{@data?.id ? -1}""" unequipOtherUpgrades: -> for slot in @data?.unequips_upgrades ? [] for upgrade in @ship.upgrades continue if upgrade.slot != slot or upgrade == this or not upgrade.isOccupied() upgrade.setData null break isOccupied: -> @data? or @occupied_by? occupyOtherUpgrades: -> for slot in @data?.also_occupies_upgrades ? [] for upgrade in @ship.upgrades continue if upgrade.slot != slot or upgrade == this or upgrade.isOccupied() @occupy upgrade break deoccupyOtherUpgrades: -> for upgrade in @occupying @deoccupy upgrade occupy: (upgrade) -> upgrade.occupied_by = this upgrade.selector.select2 'enable', false @occupying.push upgrade deoccupy: (upgrade) -> upgrade.occupied_by = null upgrade.selector.select2 'enable', true occupiesAnUpgradeSlot: (upgradeslot) -> for upgrade in @ship.upgrades continue if upgrade.slot != upgradeslot or upgrade == this or upgrade.data? if upgrade.occupied_by? and upgrade.occupied_by == this return true false toXWS: (upgrade_dict) -> (upgrade_dict[exportObj.toXWSUpgrade[@data.slot] ? @data.slot.canonicalize()] ?= []).push (@data.xws ? @data.canonical_name) class exportObj.Upgrade extends GenericAddon constructor: (args) -> # args super args @slot = args.slot @type = 'Upgrade' @dataById = exportObj.upgradesById @dataByName = exportObj.upgrades @serialization_code = 'U' @setupSelector() setupSelector: -> super width: '100%' placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'upgradePlaceholder', @slot) allowClear: true query: (query) => data = {results: []} data.results = @ship.builder.getAvailableUpgradesIncluding(@slot, @data, @ship, this, query.term, @filter_func) query.callback(data) class exportObj.RestrictedUpgrade extends exportObj.Upgrade constructor: (args) -> @filter_func = args.filter_func super args @serialization_code = 'u' if args.auto_equip? @setById args.auto_equip class exportObj.QuickbuildUpgrade extends GenericAddon constructor: (args) -> super args @slot = args.slot @type = 'Upgrade' @dataById = exportObj.upgradesById @dataByName = exportObj.upgrades @serialization_code = 'U' @upgrade = args.upgrade @setupSelector() setupSelector: -> super width: '100%' allowClear: false query: (query) => data = { results: [{ id: @upgrade.id text: if @upgrade.display_name then @upgrade.display_name else @upgrade.name points: 0 name: @upgrade.name display_name: @upgrade.display_name }] } query.callback(data) getPoints: (args) -> 0 updateSelection: (args) -> if @data? @selector.select2 'data', id: @data.id text: "#{if @data.display_name then @data.display_name else @data.name}" else @selector.select2 'data', null SERIALIZATION_CODE_TO_CLASS = 'U': exportObj.Upgrade 'u': exportObj.RestrictedUpgrade
128591
### X-Wing Squad Builder 2.0 <NAME> <<EMAIL>> https://raithos.github.io ### exportObj = exports ? this exportObj.sortHelper = (a, b) -> if a.points == b.points a_name = a.text.replace(/[^a-z0-9]/ig, '') b_name = b.text.replace(/[^a-z0-9]/ig, '') if a_name == b_name 0 else if a_name > b_name then 1 else -1 else if typeof(a.points) == "string" # handling cases where points value is "*" instead of a number 1 else if a.points > b.points then 1 else -1 exportObj.toTTS = (txt) -> if not txt? null else txt.replace(/\(.*\)/g,"").replace("�",'"').replace("�",'"') exportObj.slotsMatching = (slota, slotb) -> return true if slota == slotb return false if slota != 'HardpointShip' and slotb != 'HardpointShip' return true if slota == 'Torpedo' or slota == 'Cannon' or slota == 'Missile' return true if slotb == 'Torpedo' or slotb == 'Cannon' or slotb == 'Missile' return false $.isMobile = -> if (navigator.userAgent.match /(iPhone|iPod|iPad|Android)/i) or navigator.maxTouchPoints > 1 return true return false $.randomInt = (n) -> Math.floor(Math.random() * n) $.isElementInView = (element, fullyInView) -> pageTop = $(window).scrollTop() pageBottom = pageTop + $(window).height() elementTop = $(element).offset().top elementBottom = elementTop + $(element).height() if fullyInView return ((pageTop < elementTop) && (pageBottom > elementBottom)) else return ((elementTop <= pageBottom) && (elementBottom >= pageTop)) # ripped from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values $.getParameterByName = (name) -> name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") regexS = "[\\?&]" + name + "=([^&#]*)" regex = new RegExp(regexS) results = regex.exec(window.location.search) if results == null return "" else return decodeURIComponent(results[1].replace(/\+/g, " ")) Array::intersects = (other) -> for item in this if item in other return true return false Array::removeItem = (item) -> idx = @indexOf item @splice(idx, 1) unless idx == -1 this String::capitalize = -> @charAt(0).toUpperCase() + @slice(1) String::getXWSBaseName = -> @split('-')[0] URL_BASE = "#{window.location.protocol}//#{window.location.host}#{window.location.pathname}" SQUAD_DISPLAY_NAME_MAX_LENGTH = 24 statAndEffectiveStat = (base_stat, effective_stats, key) -> if base_stat? """#{base_stat}#{if (effective_stats? and effective_stats[key]? and effective_stats[key] != base_stat) then " (#{effective_stats[key]})" else ""}""" else if effective_stats? and effective_stats[key]? """0 (#{effective_stats[key]})""" else "0" getPrimaryFaction = (faction) -> switch faction when 'Rebel Alliance' 'Rebel Alliance' when 'Galactic Empire' 'Galactic Empire' else faction conditionToHTML = (condition) -> html = $.trim """ <div class="condition"> <div class="name">#{if condition.unique then "&middot;&nbsp;" else ""}#{if condition.display_name then condition.display_name else condition.name}</div> <div class="text">#{condition.text}</div> </div> """ # Assumes cards.js will be loaded class exportObj.SquadBuilder constructor: (args) -> # args @container = $ args.container @faction = $.trim args.faction @printable_container = $ args.printable_container @tab = $ args.tab # internal state @ships = [] @uniques_in_use = Pilot: [] Upgrade: [] Slot: [] @standard_list = Upgrade: [] Ship: [] @suppress_automatic_new_ship = false @tooltip_currently_displaying = null @randomizer_options = sources: null points: 200 bid_goal: 5 ships_or_upgrades: 3 ship_limit: 0 collection_only: true fill_zero_pts: false @total_points = 0 # a squad given in the link is loaded on construction of that builder. It will set all gamemodes of already existing builders accordingly, but we did not exists back than. So we copy over the gamemode @isHyperspace = exportObj.builders[0]?.isHyperspace ? false @isEpic = exportObj.builders[0]?.isEpic ? false @isQuickbuild = exportObj.builders[0]?.isQuickbuild ? false @backend = null @current_squad = {} @language = 'English' @collection = null @current_obstacles = [] @setupUI() @game_type_selector.val (exportObj.builders[0] ? @).game_type_selector.val() @setupEventHandlers() window.setInterval @updatePermaLink, 250 @isUpdatingPoints = false if $.getParameterByName('f') == @faction @resetCurrentSquad(true) @loadFromSerialized $.getParameterByName('d') else @resetCurrentSquad() @addShip() resetCurrentSquad: (initial_load=false) -> default_squad_name = 'Unnamed Squadron' squad_name = $.trim(@squad_name_input.val()) or default_squad_name if initial_load and $.trim $.getParameterByName('sn') squad_name = $.trim $.getParameterByName('sn') squad_obstacles = [] if initial_load and $.trim $.getParameterByName('obs') squad_obstacles = ($.trim $.getParameterByName('obs')).split(",").slice(0, 3) @current_obstacles = squad_obstacles else if @current_obstacles squad_obstacles = @current_obstacles @current_squad = id: null name: squad_name dirty: false additional_data: points: @total_points description: '' cards: [] notes: '' obstacles: squad_obstacles tag: '' faction: @faction if @total_points > 0 if squad_name == default_squad_name @current_squad.name = 'Unsaved Squadron' @current_squad.dirty = true @container.trigger 'xwing-backend:squadNameChanged' @container.trigger 'xwing-backend:squadDirtinessChanged' newSquadFromScratch: (squad_name = '<NAME> Squadron') -> @squad_name_input.val squad_name @removeAllShips() @addShip() if not @suppress_automatic_new_ship @current_obstacles = [] @resetCurrentSquad() @notes.val '' @tag.val '' setupUI: -> DEFAULT_RANDOMIZER_POINTS = 200 DEFAULT_RANDOMIZER_TIMEOUT_SEC = 4 DEFAULT_RANDOMIZER_BID_GOAL = 5 DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES = 3 DEFAULT_RANDOMIZER_SHIP_LIMIT = 0 @status_container = $ document.createElement 'DIV' @status_container.addClass 'container-fluid' @status_container.append $.trim ''' <div class="row squad-name-and-points-row"> <div class="col-md-3 squad-name-container"> <div class="display-name"> <span class="squad-name"></span> <i class="far fa-edit"></i> </div> <div class="input-append"> <input type="text" maxlength="64" placeholder="Name your squad..." /> <button class="btn save"><i class="fa fa-pen-square"></i></button> </div> <br /> <select class="game-type-selector"> <option value="standard">Extended</option> <option value="hyperspace">Hyperspace</option> <option value="epic">Epic</option> <option value="quickbuild">Quickbuild</option> </select> </div> <div class="col-md-4 points-display-container"> Points: <span class="total-points">0</span> / <input type="number" class="desired-points" value="200"> <span class="points-remaining-container">(<span class="points-remaining"></span>&nbsp;left) <span class="points-destroyed red"></span></span> <span class="content-warning unreleased-content-used d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning loading-failed-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning collection-invalid d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning ship-number-invalid-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated">A tournament legal squad must contain 2-8 ships!</span></span> <span class="content-warning multi-faction-warning-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated">Multi-Faction Lists are NEVER tournament legal!</span></span> </div> <div class="col-md-5 float-right button-container"> <div class="btn-group float-right"> <button class="btn btn-info view-as-text"><span class="d-none d-lg-block"><i class="fa fa-print"></i>&nbsp;Print/Export</span><span class="d-lg-none"><i class="fa fa-print"></i></span></button> <a class="btn btn-primary d-none collection"><span class="d-none d-lg-block"><i class="fa fa-folder-open"></i> Your Collection</span><span class="d-lg-none"><i class="fa fa-folder-open"></i></span></a> <!-- Randomize button is marked as danger, since it creates a new squad --> <button class="btn btn-danger randomize"><span class="d-none d-lg-block"><i class="fa fa-random"></i> Randomize!</span><span class="d-lg-none"><i class="fa fa-random"></i></span></button> <button class="btn btn-danger dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a class="dropdown-item randomize-options">Randomizer Options</a></li> <li><a class="dropdown-item misc-settings">Misc Settings</a></li> </ul> </div> </div> </div> <div class="row squad-save-buttons"> <div class="col-md-12"> <button class="show-authenticated btn btn-primary save-list"><i class="far fa-save"></i>&nbsp;Save</button> <button class="show-authenticated btn btn-primary save-list-as"><i class="far fa-file"></i>&nbsp;Save As...</button> <button class="show-authenticated btn btn-primary delete-list disabled"><i class="fa fa-trash"></i>&nbsp;Delete</button> <button class="show-authenticated btn btn-info backend-list-my-squads show-authenticated"><i class="fa fa-download"></i>&nbsp;Load Squad</button> <button class="btn btn-info import-squad"><i class="fa fa-file-import"></i>&nbsp;Import</button> <button class="btn btn-danger clear-squad"><i class="fa fa-plus-circle"></i>&nbsp;New Squad</button> <span class="show-authenticated backend-status"></span> </div> </div> ''' @container.append @status_container @xws_import_modal = $ document.createElement 'DIV' @xws_import_modal.addClass 'modal fade import-modal d-print-none' @xws_import_modal.tabindex = "-1" @xws_import_modal.role = "dialog" @xws_import_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>XWS Import</h3> <button type="button" class="close d-print-none" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> Import your list via XWS into YASB.<br> <i>XWS is a common format to share lists between applications.</i> <div class="container-fluid"> <textarea class="xws-content" placeholder="Paste XWS here"></textarea> </div> </div> <div class="modal-footer d-print-none"> <span class="xws-import-status"></span>&nbsp; <button class="btn btn-danger import-xws">Import</button> </div> </div> </div> """ @from_xws_button = @container.find('button.import-squad') @from_xws_button.click (e) => e.preventDefault() @xws_import_modal.find('.xws-import-status').text ' ' @xws_import_modal.modal 'show' @load_xws_button = $ @xws_import_modal.find('button.import-xws') @load_xws_button.click (e) => e.preventDefault() exportObj.loadXWSButton(@xws_import_modal) @container.append @xws_import_modal @list_modal = $ document.createElement 'DIV' @list_modal.addClass 'modal fade text-list-modal' @list_modal.tabindex = "-1" @list_modal.role = "dialog" @container.append @list_modal @list_modal.append $.trim """ <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <div class="d-print-none"> <h4 class="modal-title"><span class="squad-name"></span> (<span class="total-points"></span>)</h4> </div> <div class="d-none d-print-block"> <div class="fancy-header"> <div class="squad-name"></div> <div class="squad-faction"></div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle"> <span class="total-points"></span> </div> </div> </div> </div> <div class="fancy-under-header"></div> </div> <button type="button" class="close d-print-none" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <div class="fancy-list"></div> <div class="simple-list"></div> <div class="simplecopy-list"> <p>Copy the below and paste it elsewhere.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="reddit-list"> <p>Copy the below and paste it into your reddit post.</p> <p>Make sure that the post editor is set to markdown mode.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="tts-list"> <p>Copy the below and paste it into the Tabletop Simulator.</p> <textarea></textarea><br /><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="bbcode-list"> <p>Copy the BBCode below and paste it into your forum post.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="html-list"> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="xws-list"> <p>Copy and paste this into an XWS-compliant application. <div class="row full-row"> <div class="col d-inline-block d-none d-sm-block"><textarea></textarea><br /><button class="btn btn-modal btn-copy">Copy</button></div> <div class="col d-inline-block d-none d-sm-block qrcode-container" id="xws-qrcode-container"></div> </div> </div> </div> <div class="container-fluid modal-footer d-print-none"> <div class="row full-row"> <div class="col d-inline-block d-none d-sm-block right-col"> <label class="color-skip-text-checkbox"> Skip Card Text <input type="checkbox" class="toggle-skip-text-print" /> </label><br /> <label class="vertical-space-checkbox"> Add Space for Cards <input type="checkbox" class="toggle-vertical-space" /> </label><br /> <label class="maneuver-print-checkbox"> Include Maneuvers Chart <input type="checkbox" class="toggle-maneuver-print" /> </label><br /> <label class="expanded-shield-hull-print-checkbox"> Expand Shield and Hull <input type="checkbox" class="toggle-expanded-shield-hull-print" /> </label> </div> <div class="col d-inline-block d-none d-sm-block right-col"> <label class="color-print-checkbox"> Print Color <input type="checkbox" class="toggle-color-print" checked="checked" /> </label><br /> <label class="qrcode-checkbox"> Include QR codes <input type="checkbox" class="toggle-juggler-qrcode" checked="checked" /> </label><br /> <label class="obstacles-checkbox"> Include Obstacle Choices <input type="checkbox" class="toggle-obstacles" /> </label> </div> </div> <div class="row btn-group list-display-mode"> <button class="btn btn-modal select-simple-view">Simple</button> <button class="btn btn-modal select-fancy-view d-none d-sm-block">Fancy</button> <button class="btn btn-modal select-simplecopy-view">Text</button> <button class="btn btn-modal select-tts-view">TTS</button> <button class="btn btn-modal select-reddit-view">Reddit</button> <button class="btn btn-modal select-bbcode-view">BBCode</button> <button class="btn btn-modal select-html-view">HTML</button> <button class="btn btn-modal select-xws-view">XWS</button> </div> <button class="btn btn-modal print-list d-none d-sm-block"><i class="fa fa-print"></i>&nbsp;Print</button> </div> </div> </div> """ @fancy_container = $ @list_modal.find('.fancy-list') @fancy_total_points_container = $ @list_modal.find('div.modal-header .total-points') @simple_container = $ @list_modal.find('div.modal-body .simple-list') @reddit_container = $ @list_modal.find('div.modal-body .reddit-list') @reddit_textarea = $ @reddit_container.find('textarea') @reddit_textarea.attr 'readonly', 'readonly' @simplecopy_container = $ @list_modal.find('div.modal-body .simplecopy-list') @simplecopy_textarea = $ @simplecopy_container.find('textarea') @simplecopy_textarea.attr 'readonly', 'readonly' @tts_container = $ @list_modal.find('div.modal-body .tts-list') @tts_textarea = $ @tts_container.find('textarea') @tts_textarea.attr 'readonly', 'readonly' @xws_container = $ @list_modal.find('div.modal-body .xws-list') @xws_textarea = $ @xws_container.find('textarea') @xws_textarea.attr 'readonly', 'readonly' @bbcode_container = $ @list_modal.find('div.modal-body .bbcode-list') @bbcode_textarea = $ @bbcode_container.find('textarea') @bbcode_textarea.attr 'readonly', 'readonly' @htmlview_container = $ @list_modal.find('div.modal-body .html-list') @html_textarea = $ @htmlview_container.find('textarea') @html_textarea.attr 'readonly', 'readonly' @toggle_vertical_space_container = $ @list_modal.find('.vertical-space-checkbox') @toggle_color_print_container = $ @list_modal.find('.color-print-checkbox') @toggle_color_skip_text = $ @list_modal.find('.color-skip-text-checkbox') @toggle_maneuver_dial_container = $ @list_modal.find('.maneuver-print-checkbox') @toggle_expanded_shield_hull_container = $ @list_modal.find('.expanded-shield-hull-print-checkbox') @toggle_qrcode_container = $ @list_modal.find('.qrcode-checkbox') @toggle_obstacle_container = $ @list_modal.find('.obstacles-checkbox') @btn_print_list = ($ @list_modal.find('.print-list'))[0] @list_modal.on 'click', 'button.btn-copy', (e) => @self = $(e.currentTarget) @self.siblings('textarea').select() @success = document.execCommand('copy') if @success @self.addClass 'btn-success' setTimeout ( => @self.removeClass 'btn-success' ), 1000 @select_simple_view_button = $ @list_modal.find('.select-simple-view') @select_simple_view_button.click (e) => @select_simple_view_button.blur() unless @list_display_mode == 'simple' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_simple_view_button.addClass 'btn-inverse' @list_display_mode = 'simple' @simple_container.show() @fancy_container.hide() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @xws_container.hide() @bbcode_container.hide() @htmlview_container.hide() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.show() @toggle_obstacle_container.show() @btn_print_list.disabled = false; @select_fancy_view_button = $ @list_modal.find('.select-fancy-view') @select_fancy_view_button.click (e) => @select_fancy_view_button.blur() unless @list_display_mode == 'fancy' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_fancy_view_button.addClass 'btn-inverse' @list_display_mode = 'fancy' @fancy_container.show() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @bbcode_container.hide() @htmlview_container.hide() @xws_container.hide() @toggle_vertical_space_container.show() @toggle_color_print_container.show() @toggle_color_skip_text.show() @toggle_maneuver_dial_container.show() @toggle_expanded_shield_hull_container.show() @toggle_qrcode_container.show() @toggle_obstacle_container.show() @btn_print_list.disabled = false; @select_reddit_view_button = $ @list_modal.find('.select-reddit-view') @select_reddit_view_button.click (e) => @select_reddit_view_button.blur() unless @list_display_mode == 'reddit' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_reddit_view_button.addClass 'btn-inverse' @list_display_mode = 'reddit' @reddit_container.show() @simplecopy_container.hide() @bbcode_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @reddit_textarea.select() @reddit_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_simplecopy_view_button = $ @list_modal.find('.select-simplecopy-view') @select_simplecopy_view_button.click (e) => @select_simplecopy_view_button.blur() unless @list_display_mode == 'simplecopy' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_simplecopy_view_button.addClass 'btn-inverse' @list_display_mode = 'simplecopy' @reddit_container.hide() @simplecopy_container.show() @bbcode_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @simplecopy_textarea.select() @simplecopy_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_tts_view_button = $ @list_modal.find('.select-tts-view') @select_tts_view_button.click (e) => @select_tts_view_button.blur() unless @list_display_mode == 'tts' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_tts_view_button.addClass 'btn-inverse' @list_display_mode = 'tts' @tts_container.show() @bbcode_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @fancy_container.hide() @tts_textarea.select() @tts_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_bbcode_view_button = $ @list_modal.find('.select-bbcode-view') @select_bbcode_view_button.click (e) => @select_bbcode_view_button.blur() unless @list_display_mode == 'bbcode' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_bbcode_view_button.addClass 'btn-inverse' @list_display_mode = 'bbcode' @bbcode_container.show() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @bbcode_textarea.select() @bbcode_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_html_view_button = $ @list_modal.find('.select-html-view') @select_html_view_button.click (e) => @select_html_view_button.blur() unless @list_display_mode == 'html' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_html_view_button.addClass 'btn-inverse' @list_display_mode = 'html' @reddit_container.hide() @simplecopy_container.hide() @tts_container.hide() @bbcode_container.hide() @htmlview_container.show() @simple_container.hide() @fancy_container.hide() @xws_container.hide() @html_textarea.select() @html_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_xws_view_button = $ @list_modal.find('.select-xws-view') @select_xws_view_button.click (e) => @select_xws_view() if $(window).width() >= 768 @simple_container.hide() @select_fancy_view_button.click() else @select_simple_view_button.click() @clear_squad_button = $ @status_container.find('.clear-squad') @clear_squad_button.click (e) => if @current_squad.dirty and @backend? @backend.warnUnsaved this, () => @newSquadFromScratch() else @newSquadFromScratch() @squad_name_container = $ @status_container.find('div.squad-name-container') @squad_name_display = $ @container.find('.display-name') @squad_name_placeholder = $ @container.find('.squad-name') @squad_name_input = $ @squad_name_container.find('input') @squad_name_save_button = $ @squad_name_container.find('button.save') @squad_name_input.closest('div').hide() @points_container = $ @status_container.find('div.points-display-container') @total_points_span = $ @points_container.find('.total-points') @game_type_selector = $ @status_container.find('.game-type-selector') @game_type_selector.select2 minimumResultsForSearch: -1 @game_type_selector.change (e) => # $(window).trigger 'xwing:gameTypeChanged', @game_type_selector.val() @onGameTypeChanged @game_type_selector.val() @desired_points_input = $ @points_container.find('.desired-points') @desired_points_input.change (e) => @onPointsUpdated $.noop @points_remaining_span = $ @points_container.find('.points-remaining') @points_destroyed_span = $ @points_container.find('.points-destroyed') @points_remaining_container = $ @points_container.find('.points-remaining-container') @unreleased_content_used_container = $ @points_container.find('.unreleased-content-used') @loading_failed_container = $ @points_container.find('.loading-failed-container') @ship_number_invalid_container = $ @points_container.find('.ship-number-invalid-container') @multi_faction_warning_container = $ @points_container.find('.multi-faction-warning-container') @collection_invalid_container = $ @points_container.find('.collection-invalid') @view_list_button = $ @status_container.find('div.button-container button.view-as-text') @randomize_button = $ @status_container.find('div.button-container button.randomize') @customize_randomizer = $ @status_container.find('div.button-container a.randomize-options') @misc_settings = $ @status_container.find('div.button-container a.misc-settings') @backend_status = $ @status_container.find('.backend-status') @backend_status.hide() @collection_button = $ @status_container.find('div.button-container a.collection') @collection_button.click (e) => e.preventDefault() unless @collection_button.prop('disabled') @collection.modal.modal 'show' @squad_name_input.keypress (e) => if e.which == 13 @squad_name_save_button.click() false @squad_name_input.change (e) => @backend_status.fadeOut 'slow' @squad_name_input.blur (e) => @squad_name_input.change() @squad_name_save_button.click() @squad_name_display.click (e) => e.preventDefault() @squad_name_display.hide() @squad_name_input.val $.trim(@current_squad.name) # Because Firefox handles this badly window.setTimeout () => @squad_name_input.focus() @squad_name_input.select() , 100 @squad_name_input.closest('div').show() @squad_name_save_button.click (e) => e.preventDefault() @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' name = @current_squad.name = $.trim(@squad_name_input.val()) if name.length > 0 @squad_name_display.show() @container.trigger 'xwing-backend:squadNameChanged' @squad_name_input.closest('div').hide() @randomizer_options_modal = $ document.createElement('DIV') @randomizer_options_modal.addClass 'modal fade randomizer-modal' @randomizer_options_modal.tabindex = "-1" @randomizer_options_modal.role = "dialog" $('body').append @randomizer_options_modal @randomizer_options_modal.append $.trim """ <div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Random Squad Builder Options</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <form> <label> Maximal desired bid <input type="number" class="randomizer-bid-goal" value="#{DEFAULT_RANDOMIZER_BID_GOAL}" placeholder="#{DEFAULT_RANDOMIZER_BID_GOAL}" /> </label><br /> <label> Maximum Ship Count (0 for no limit) <input type="number" class="randomizer-ship-limit" value="#{DEFAULT_RANDOMIZER_SHIP_LIMIT}" placeholder="#{DEFAULT_RANDOMIZER_SHIP_LIMIT}" /> </label><br /> <label> More upgrades <input type="range" min="0" max="10" class="randomizer-ships-or-upgrades" value="#{DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES}" placeholder="#{DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES}" /> Less upgrades </label><br /> <label> <input type="checkbox" class="randomizer-collection-only" checked="checked"/> Only use items from collection </label><br /> <label> Sets and Expansions (default all) <select class="randomizer-sources" multiple="1" data-placeholder="Use all sets and expansions"> </select> </label><br /> <label> <input type="checkbox" class="randomizer-fill-zero-pts" /> Always fill 0-point slots </label><br /> <label> Maximum Seconds to Spend Randomizing <input type="number" class="randomizer-timeout" value="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" placeholder="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" /> </label> </form> </div> <div class="modal-footer"> <button class="btn btn-primary do-randomize" aria-hidden="true">Randomize!</button> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @randomizer_source_selector = $ @randomizer_options_modal.find('select.randomizer-sources') for expansion in exportObj.expansions opt = $ document.createElement('OPTION') opt.text expansion @randomizer_source_selector.append opt @randomizer_source_selector.select2 width: "100%" minimumResultsForSearch: if $.isMobile() then -1 else 0 @randomizer_collection_selector = ($ @randomizer_options_modal.find('.randomizer-collection-only'))[0] @randomizer_fill_zero_pts = ($ @randomizer_options_modal.find('.randomizer-fill-zero-pts'))[0] @randomize_button.click (e) => e.preventDefault() if @current_squad.dirty and @backend? @backend.warnUnsaved this, () => @randomize_button.click() else points = parseInt @desired_points_input.val() points = DEFAULT_RANDOMIZER_POINTS if (isNaN(points) or points <= 0) bid_goal = parseInt $(@randomizer_options_modal.find('.randomizer-bid-goal')).val() bid_goal = DEFAULT_RANDOMIZER_BID_GOAL if (isNaN(bid_goal) or bid_goal < 0) ship_limit = parseInt $(@randomizer_options_modal.find('.randomizer-ship-limit')).val() ship_limit = DEFAULT_RANDOMIZER_SHIP_LIMIT if (isNaN(ship_limit) or ship_limit < 0) ships_or_upgrades = parseInt $(@randomizer_options_modal.find('.randomizer-ships-or-upgrades')).val() ships_or_upgrades = DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES if (isNaN(ships_or_upgrades) or ships_or_upgrades < 0) timeout_sec = parseInt $(@randomizer_options_modal.find('.randomizer-timeout')).val() timeout_sec = DEFAULT_RANDOMIZER_TIMEOUT_SEC if (isNaN(timeout_sec) or timeout_sec <= 0) # console.log "points=#{points}, sources=#{@randomizer_source_selector.val()}, timeout=#{timeout_sec}" @randomSquad(points, @randomizer_source_selector.val(), timeout_sec * 1000, bid_goal, ship_limit, ships_or_upgrades, @randomizer_collection_selector.checked, @randomizer_fill_zero_pts.checked) @randomizer_options_modal.find('button.do-randomize').click (e) => e.preventDefault() @randomizer_options_modal.modal('hide') @randomize_button.click() @customize_randomizer.click (e) => e.preventDefault() @randomizer_options_modal.modal() @misc_settings_modal = $ document.createElement('DIV') @misc_settings_modal.addClass 'modal fade' @misc_settings_modal.tabindex = "-1" @misc_settings_modal.role = "dialog" $('body').append @misc_settings_modal @misc_settings_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Miscellaneous Settings</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <label class = "toggle-initiative-prefix-names misc-settings-label"> <input type="checkbox" class="initiative-prefix-names-checkbox misc-settings-checkbox" /> Put INI as prefix in front of names. </label><br /> <label> <input type="checkbox" checked /> Is <NAME> the worst? </label> </div> <div class="modal-footer"> <span class="misc-settings-infoline"></span> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @misc_settings_infoline = $ @misc_settings_modal.find('.misc-settings-infoline') @misc_settings_initiative_prefix = $ @misc_settings_modal.find('.initiative-prefix-names-checkbox') if @backend? @backend.getSettings (st) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = st.showInitiativeInFrontOfPilotName? if st.showInitiativeInFrontOfPilotName? @misc_settings_initiative_prefix.prop('checked', true) else @waiting_for_backend ?= [] @waiting_for_backend.push => @backend.getSettings (st) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = st.showInitiativeInFrontOfPilotName? if st.showInitiativeInFrontOfPilotName? @misc_settings_initiative_prefix.prop('checked', true) @misc_settings_initiative_prefix.click (e) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = @misc_settings_initiative_prefix.prop('checked') if @backend? if @misc_settings_initiative_prefix.prop('checked') @backend.set 'showInitiativeInFrontOfPilotName', '1', (ds) => @misc_settings_infoline.text "Changes Saved" @misc_settings_infoline.fadeIn 100, => @misc_settings_infoline.fadeOut 3000 else @backend.deleteSetting 'showInitiativeInFrontOfPilotName', (dd) => @misc_settings_infoline.text "Changes Saved" @misc_settings_infoline.fadeIn 100, => @misc_settings_infoline.fadeOut 3000 @misc_settings.click (e) => e.preventDefault() @misc_settings_modal.modal() @misc_settings_initiative_prefix.prop('checked', exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix) @choose_obstacles_modal = $ document.createElement 'DIV' @choose_obstacles_modal.addClass 'modal fade choose-obstacles-modal' @choose_obstacles_modal.tabindex = "-1" @choose_obstacles_modal.role = "dialog" @container.append @choose_obstacles_modal @choose_obstacles_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <label class='choose-obstacles-description'>Choose up to three obstacles, to include in the permalink for use in external programs</label> </div> <div class="modal-body"> <div class="obstacle-select-container" style="float:left"> <select multiple class='obstacle-select' size="18"> <option class="coreasteroid0-select" value="coreasteroid0">Core Asteroid 0</option> <option class="coreasteroid1-select" value="coreasteroid1">Core Asteroid 1</option> <option class="coreasteroid2-select" value="coreasteroid2">Core Asteroid 2</option> <option class="coreasteroid3-select" value="coreasteroid3">Core Asteroid 3</option> <option class="coreasteroid4-select" value="coreasteroid4">Core Asteroid 4</option> <option class="coreasteroid5-select" value="coreasteroid5">Core Asteroid 5</option> <option class="yt2400debris0-select" value="yt2400debris0">YT2400 Debris 0</option> <option class="yt2400debris1-select" value="yt2400debris1">YT2400 Debris 1</option> <option class="yt2400debris2-select" value="yt2400debris2">YT2400 Debris 2</option> <option class="vt49decimatordebris0-select" value="vt49decimatordebris0">VT49 Debris 0</option> <option class="vt49decimatordebris1-select" value="vt49decimatordebris1">VT49 Debris 1</option> <option class="vt49decimatordebris2-select" value="vt49decimatordebris2">VT49 Debris 2</option> <option class="core2asteroid0-select" value="core2asteroid0">Force Awakens Asteroid 0</option> <option class="core2asteroid1-select" value="core2asteroid1">Force Awakens Asteroid 1</option> <option class="core2asteroid2-select" value="core2asteroid2">Force Awakens Asteroid 2</option> <option class="core2asteroid3-select" value="core2asteroid3">Force Awakens Asteroid 3</option> <option class="core2asteroid4-select" value="core2asteroid4">Force Awakens Asteroid 4</option> <option class="core2asteroid5-select" value="core2asteroid5">Force Awakens Asteroid 5</option> <option class="gascloud1-select" value="gascloud1">Gas Cloud 1</option> <option class="gascloud2-select" value="gascloud2">Gas Cloud 2</option> <option class="gascloud3-select" value="gascloud3">Gas Cloud 3</option> <option class="gascloud4-select" value="gascloud4">Gas Cloud 4</option> <option class="gascloud5-select" value="gascloud5">Gas Cloud 5</option> <option class="gascloud6-select" value="gascloud6">Gas Cloud 6</option> </select> </div> <div class="obstacle-image-container" style="display:none;"> <img class="obstacle-image" src="images/core2asteroid0.png" /> </div> </div> <div class="modal-footer d-print-none"> <button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @obstacles_select = @choose_obstacles_modal.find('.obstacle-select') @obstacles_select_image = @choose_obstacles_modal.find('.obstacle-image-container') # Backend @backend_list_squads_button = $ @container.find('button.backend-list-my-squads') @backend_list_squads_button.click (e) => e.preventDefault() if @backend? @backend.list this @backend_save_list_button = $ @container.find('button.save-list') @backend_save_list_button.click (e) => e.preventDefault() if @backend? and not @backend_save_list_button.hasClass('disabled') additional_data = points: @total_points description: @describeSquad() cards: @listCards() notes: @notes.val().substr(0, 1024) obstacles: @getObstacles() tag: @tag.val().substr(0, 1024) @backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;Saving squad... """ @backend_status.show() @backend_save_list_button.addClass 'disabled' await @backend.save @serialize(), @current_squad.id, @current_squad.name, @faction, additional_data, defer(results) if results.success @current_squad.dirty = false if @current_squad.id? @backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;Squad updated successfully. """ else @backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;New squad saved successfully. """ @current_squad.id = results.id @container.trigger 'xwing-backend:squadDirtinessChanged' else @backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ @backend_save_list_button.removeClass 'disabled' @backend_save_list_as_button = $ @container.find('button.save-list-as') @backend_save_list_as_button.addClass 'disabled' @backend_save_list_as_button.click (e) => e.preventDefault() if @backend? and not @backend_save_list_as_button.hasClass('disabled') @backend.showSaveAsModal this @backend_delete_list_button = $ @container.find('button.delete-list') @backend_delete_list_button.click (e) => e.preventDefault() if @backend? and not @backend_delete_list_button.hasClass('disabled') @backend.showDeleteModal this content_container = $ document.createElement 'DIV' content_container.addClass 'container-fluid' @container.append content_container content_container.append $.trim """ <div class="row"> <div class="col-md-9 ship-container"> <label class="notes-container show-authenticated col-md-10"> <span class="notes-name">Squad Notes:</span> <br /> <textarea class="squad-notes"></textarea> <br /> <span class="tag-name">Tag:</span> <input type="search" class="squad-tag"></input> </label> <div class="obstacles-container"> <button class="btn btn-info choose-obstacles"><i class="fa fa-cloud"></i>&nbsp;Choose Obstacles</button> </div> </div> <div class="col-md-3 info-container" id="info-container"> </div> </div> """ @ship_container = $ content_container.find('div.ship-container') @info_container = $ content_container.find('div.info-container') @obstacles_container = content_container.find('.obstacles-container') @notes_container = $ content_container.find('.notes-container') @notes = $ @notes_container.find('textarea.squad-notes') @tag = $ @notes_container.find('input.squad-tag') @info_container.append $.trim @createInfoContainerUI() @info_container.hide() @print_list_button = $ @container.find('button.print-list') @container.find('[rel=tooltip]').tooltip() # obstacles @obstacles_button = $ @container.find('button.choose-obstacles') @obstacles_button.click (e) => e.preventDefault() @showChooseObstaclesModal() # conditions @condition_container = $ document.createElement('div') @condition_container.addClass 'conditions-container d-flex flex-wrap' @container.append @condition_container @mobile_tooltip_modal = $ document.createElement 'DIV' @mobile_tooltip_modal.addClass 'modal fade choose-obstacles-modal d-print-none' @mobile_tooltip_modal.tabindex = "-1" @mobile_tooltip_modal.role = "dialog" @container.append @mobile_tooltip_modal @mobile_tooltip_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> </div> <div class="modal-body"> """ + @createInfoContainerUI() + """ </div> <div class="modal-footer"> <button class="btn btn-danger close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ createInfoContainerUI: -> return """ <div class="card info-well"> <div class="info-name"></div> <div class="info-type"></div> <span class="info-collection"></span> <table class="table-sm"> <tbody> <tr class="info-ship"> <td class="info-header">Ship</td> <td class="info-data"></td> </tr> <tr class="info-base"> <td class="info-header">Base</td> <td class="info-data"></td> </tr> <tr class="info-skill"> <td class="info-header">Initiative</td> <td class="info-data info-skill"></td> </tr> <tr class="info-engagement"> <td class="info-header">Engagement</td> <td class="info-data info-engagement"></td> </tr> <tr class="info-attack-bullseye"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-fullfront"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-left"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-leftarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-right"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-rightarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-back"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-turret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-doubleturret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-agility"> <td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td> <td class="info-data info-agility"></td> </tr> <tr class="info-hull"> <td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td> <td class="info-data info-hull"></td> </tr> <tr class="info-shields"> <td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td> <td class="info-data info-shields"></td> </tr> <tr class="info-force"> <td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td> <td class="info-data info-force"></td> </tr> <tr class="info-charge"> <td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td> <td class="info-data info-charge"></td> </tr> <tr class="info-energy"> <td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td> <td class="info-data info-energy"></td> </tr> <tr class="info-range"> <td class="info-header">Range</td> <td class="info-data info-range"></td><td class="info-rangebonus"><i class="xwing-miniatures-font red header-range xwing-miniatures-font-rangebonusindicator"></i></td> </tr> <tr class="info-actions"> <td class="info-header">Actions</td> <td class="info-data"></td> </tr> <tr class="info-upgrades"> <td class="info-header">Upgrades</td> <td class="info-data"></td> </tr> </tbody> </table> <p class="info-restrictions"></p> <p class="info-text"></p> <p class="info-maneuvers"></p> <br /> <span class="info-header info-sources">Sources:</span> <span class="info-data info-sources"></span> </div> """ setupEventHandlers: -> @container.on 'xwing:claimUnique', (e, unique, type, cb) => @claimUnique unique, type, cb .on 'xwing:releaseUnique', (e, unique, type, cb) => @releaseUnique unique, type, cb .on 'xwing:pointsUpdated', (e, cb=$.noop) => if @isUpdatingPoints cb() else @isUpdatingPoints = true @onPointsUpdated () => @isUpdatingPoints = false cb() .on 'xwing-backend:squadLoadRequested', (e, squad, cb=$.noop) => @onSquadLoadRequested squad cb() .on 'xwing-backend:squadDirtinessChanged', (e) => @onSquadDirtinessChanged() .on 'xwing-backend:squadNameChanged', (e) => @onSquadNameChanged() .on 'xwing:beforeLanguageLoad', (e, cb=$.noop) => @pretranslation_serialized = @serialize() cb() .on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) => if @language != language @language = language old_dirty = @current_squad.dirty if @pretranslation_serialized.length? @loadFromSerialized @pretranslation_serialized for ship in @ships ship.updateSelections() @current_squad.dirty = old_dirty @pretranslation_serialized = undefined cb() # Recently moved this here. Did this ever work? .on 'xwing:shipUpdated', (e, cb=$.noop) => all_allocated = true for ship in @ships ship.updateSelections() if ship.ship_selector.val() == '' all_allocated = false #console.log "all_allocated is #{all_allocated}, suppress_automatic_new_ship is #{@suppress_automatic_new_ship}" #console.log "should we add ship: #{all_allocated and not @suppress_automatic_new_ship}" @addShip() if all_allocated and not @suppress_automatic_new_ship $(window).on 'xwing-backend:authenticationChanged', (e) => @resetCurrentSquad() .on 'xwing-collection:created', (e, collection) => # console.log "#{@faction}: collection was created" @collection = collection # console.log "#{@faction}: Collection created, checking squad" @collection.onLanguageChange null, @language @checkCollection() @collection_button.removeClass 'd-none' .on 'xwing-collection:changed', (e, collection) => # console.log "#{@faction}: Collection changed, checking squad" @checkCollection() .on 'xwing-collection:destroyed', (e, collection) => @collection = null @collection_button.addClass 'd-none' .on 'xwing:pingActiveBuilder', (e, cb) => cb(this) if @container.is(':visible') .on 'xwing:activateBuilder', (e, faction, cb) => if faction == @faction @tab.tab('show') cb this .on 'xwing:gameTypeChanged', (e, gameType, cb=$.noop) => @onGameTypeChanged gameType, cb if @game_type_selector.val() != gameType @game_type_selector.val(gameType).trigger('change') @obstacles_select.change (e) => if @obstacles_select.val().length > 3 @obstacles_select.val(@current_squad.additional_data.obstacles) else previous_obstacles = @current_squad.additional_data.obstacles @current_obstacles = (o for o in @obstacles_select.val()) if (previous_obstacles?) new_selection = @current_obstacles.filter((element) => return previous_obstacles.indexOf(element) == -1) else new_selection = @current_obstacles if new_selection.length > 0 @showChooseObstaclesSelectImage(new_selection[0]) @current_squad.additional_data.obstacles = @current_obstacles @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' @container.trigger 'xwing:pointsUpdated' @view_list_button.click (e) => e.preventDefault() @showTextListModal() @print_list_button.click (e) => e.preventDefault() # Copy text list to printable @printable_container.find('.printable-header').html @list_modal.find('.modal-header').html() @printable_container.find('.printable-body').text '' switch @list_display_mode when 'simple' @printable_container.find('.printable-body').html @simple_container.html() else for ship in @ships @printable_container.find('.printable-body').append ship.toHTML() if ship.pilot? @printable_container.find('.fancy-ship').toggleClass 'tall', @list_modal.find('.toggle-vertical-space').prop('checked') @printable_container.find('.printable-body').toggleClass 'bw', not @list_modal.find('.toggle-color-print').prop('checked') if @list_modal.find('.toggle-skip-text-print').prop('checked') for text in @printable_container.find('.upgrade-text, .fancy-pilot-text') text.hidden = true if @list_modal.find('.toggle-maneuver-print').prop('checked') @printable_container.find('.printable-body').append @getSquadDialsAsHTML() expanded_hull_and_shield = @list_modal.find('.toggle-expanded-shield-hull-print').prop('checked') for container in @printable_container.find('.expanded-hull-or-shield') container.hidden = not expanded_hull_and_shield for container in @printable_container.find('.simple-hull-or-shield') container.hidden = expanded_hull_and_shield faction = switch @faction when 'Rebel Alliance' 'rebel' when 'Galactic Empire' 'empire' when 'Scum and Villainy' 'scum' when 'Resistance' 'rebel-outline' when 'First Order' 'firstorder' when 'Galactic Republic' 'republic' when 'Separatist Alliance' 'separatists' when 'All' 'first-player-4' @printable_container.find('.squad-faction').html """<i class="xwing-miniatures-font xwing-miniatures-font-#{faction}"></i>""" # List type if @isHyperspace @printable_container.find('.squad-name').append """ <i class="xwing-miniatures-font xwing-miniatures-font-first-player-1"></i>""" if @isEpic @printable_container.find('.squad-name').append """ <i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>""" # Notes, if present @printable_container.find('.printable-body').append $.trim """ <div class="version">Points Version: 1.9.0 March 2021</div> """ if $.trim(@notes.val()) != '' @printable_container.find('.printable-body').append $.trim """ <h5 class="print-notes">Notes:</h5> <pre class="print-notes"></pre> """ @printable_container.find('.printable-body pre.print-notes').text @notes.val() else # Conditions @printable_container.find('.printable-body').append $.trim """ <div class="print-conditions"></div> """ @printable_container.find('.printable-body .print-conditions').html @condition_container.html() # Obstacles if @list_modal.find('.toggle-obstacles').prop('checked') @printable_container.find('.printable-body').append $.trim """ <div class="obstacles"> <div>Mark the three obstacles you are using.</div> <img class="obstacle-silhouettes" src="images/xws-obstacles.png" /> </div> """ # Add List Juggler QR code query = @getPermaLinkParams(['sn', 'obs']) if query? and @list_modal.find('.toggle-juggler-qrcode').prop('checked') @printable_container.find('.printable-body').append $.trim """ <div class="qrcode-container"> <div class="permalink-container"> <div class="qrcode"></div> <div class="qrcode-text">Scan to open this list in the builder</div> </div> <div class="juggler-container"> <div class="qrcode"></div> <div class="qrcode-text">For List Juggler (When it's updated for 2.0)</div> </div> </div> """ text = "https://yasb-xws.herokuapp.com/juggler#{query}" @printable_container.find('.juggler-container .qrcode').qrcode render: 'div' ec: 'M' size: if text.length < 144 then 144 else 160 text: text text = "https://raithos.github.io/#{query}" @printable_container.find('.permalink-container .qrcode').qrcode render: 'div' ec: 'M' size: if text.length < 144 then 144 else 160 text: text window.print() $(window).resize => @select_simple_view_button.click() if $(window).width() < 768 and @list_display_mode != 'simple' for ship in @ships ship.checkPilotSelectorQueryModal() @notes.change @onNotesUpdated @tag.change @onNotesUpdated @notes.on 'keyup', @onNotesUpdated @tag.on 'keyup', @onNotesUpdated getPermaLinkParams: (ignored_params=[]) => params = {} params.f = encodeURI(@faction) unless 'f' in ignored_params params.d = encodeURI(@serialize()) unless 'd' in ignored_params params.sn = encodeURIComponent(@current_squad.name) unless 'sn' in ignored_params params.obs = encodeURI(@current_squad.additional_data.obstacles || '') unless 'obs' in ignored_params return "?" + ("#{k}=#{v}" for k, v of params).join("&") getPermaLink: (params=@getPermaLinkParams()) => "#{URL_BASE}#{params}" updatePermaLink: () => return unless @container.is(':visible') # gross but couldn't make clearInterval work next_params = @getPermaLinkParams() if window.location.search != next_params window.history.replaceState(next_params, '', @getPermaLink(next_params)) onNotesUpdated: => if @total_points > 0 @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' onGameTypeChanged: (gametype, cb=$.noop) => oldHyperspace = @isHyperspace oldEpic = @isEpic oldQuickbuild = @isQuickbuild @isHyperspace = false @isEpic = false @isQuickbuild = false switch gametype when 'standard' @desired_points_input.val 200 when 'hyperspace' @isHyperspace = true @desired_points_input.val 200 when 'epic' @isEpic = true @desired_points_input.val 500 when 'quickbuild' @isQuickbuild = true @desired_points_input.val 8 if oldQuickbuild != @isQuickbuild old_id = @current_squad.id @newSquadFromScratch($.trim(@current_squad.name)) @current_squad.id = old_id # we want to keep the ID, so we allow people to use the save button else old_id = @current_squad.id @container.trigger 'xwing:pointsUpdated', $.noop @container.trigger 'xwing:shipUpdated' cb() addStandardizedToList: (ship) -> if ship.data?.name? idx = @standard_list['Ship'].indexOf ship.data.name if idx > -1 for ship_upgrade in ship.upgrades if ship_upgrade.slot == @standard_list['Upgrade'][idx].slot ship_upgrade.setData @standard_list['Upgrade'][idx] break onPointsUpdated: (cb=$.noop) => tot_points = 0 points_dest = 0 unreleased_content_used = false # validating may remove the ship, if not only some upgrade, but the pilot himself is not valid. Thus iterate backwards over the array, so that is probably fine? for i in [@ships.length - 1 ... -1] ship = @ships[i] ship.validate() continue unless ship # if the ship has been removed, we no longer care about it # Standardized Loop, will integrate later for efficiency @addStandardizedToList(ship) tot_points += ship.getPoints() if ship.destroystate == 1 points_dest += Math.ceil ship.getPoints() / 2 else if ship.destroystate == 2 points_dest += ship.getPoints() ship_uses_unreleased_content = ship.checkUnreleasedContent() unreleased_content_used = ship_uses_unreleased_content if ship_uses_unreleased_content @total_points = tot_points @points_destroyed = points_dest @total_points_span.text @total_points points_left = parseInt(@desired_points_input.val()) - @total_points points_destroyed = parseInt(@total_points) @points_remaining_span.text points_left @points_destroyed_span.html if points_dest != 0 then """<i class="xwing-miniatures-font xwing-miniatures-font-hit"></i>#{points_dest}""" else "" @points_remaining_container.toggleClass 'red', (points_left < 0) @unreleased_content_used_container.toggleClass 'd-none', not unreleased_content_used @fancy_total_points_container.text @total_points # update text list @fancy_container.text '' @simple_container.html '<table class="simple-table"></table>' simplecopy_ships = [] reddit_ships = [] tts_ships = [] bbcode_ships = [] htmlview_ships = [] for ship in @ships if ship.pilot? @fancy_container.append ship.toHTML() #for dial in @fancy_container.find('.fancy-dial') #dial.hidden = true @simple_container.find('table').append ship.toTableRow() simplecopy_ships.push ship.toSimpleCopy() reddit_ships.push ship.toRedditText() tts_ships.push ship.toTTSText() bbcode_ships.push ship.toBBCode() htmlview_ships.push ship.toSimpleHTML() @htmlview_container.find('textarea').val $.trim """#{htmlview_ships.join '<br />'} <br /> <b><i>Total: #{@total_points}</i></b> <br /> <a href="#{@getPermaLink()}">View in Yet Another Squad Builder 2.0</a> """ @reddit_container.find('textarea').val $.trim """#{reddit_ships.join " \n"} \n**Total:** *#{@total_points}* \n \n[View in Yet Another Squad Builder 2.0](#{@getPermaLink()})""" @simplecopy_container.find('textarea').val $.trim """#{simplecopy_ships.join ""} \nTotal: #{@total_points} \n \nView in Yet Another Squad Builder 2.0: #{@getPermaLink()}""" #Additional code to add obstacles to TTS obstacles = @getObstacles() if (obstacles? and obstacles.length > 0) and (tts_ships.length > 0) tts_ships[tts_ships.length - 1] = tts_ships[tts_ships.length - 1].slice(0, -2) tts_obstacles = ' |' for obstacle in obstacles if obstacle? tts_obstacles += """ #{obstacle} /""" tts_obstacles = tts_obstacles.slice(0, -1) tts_ships.push tts_obstacles @tts_textarea.val $.trim """#{tts_ships.join ""}""" @bbcode_container.find('textarea').val $.trim """#{bbcode_ships.join "\n\n"}\n[b][i]Total: #{@total_points}[/i][/b]\n\n[url=#{@getPermaLink()}]View in Yet Another Squad Builder 2.0[/url]""" # console.log "#{@faction}: Squad updated, checking collection" @checkCollection() # update conditions used # this old version of phantomjs i'm using doesn't support Set if Set? conditions_set = new Set() for ship in @ships # shouldn't there be a set union ship.getConditions().forEach (condition) -> conditions_set.add(condition) conditions = [] conditions_set.forEach (condition) -> conditions.push(condition) conditions.sort (a, b) -> if a.name.canonicalize() < b.name.canonicalize() -1 else if b.name.canonicalize() > a.name.canonicalize() 1 else 0 @condition_container.text '' conditions.forEach (condition) => @condition_container.append conditionToHTML(condition) cb @total_points onSquadLoadRequested: (squad) => # console.log(squad.additional_data.obstacles) @current_squad = squad @backend_delete_list_button.removeClass 'disabled' @squad_name_input.val @current_squad.name @squad_name_placeholder.text @current_squad.name @current_obstacles = @current_squad.additional_data.obstacles @updateObstacleSelect(@current_squad.additional_data.obstacles) if squad.serialized.length? @loadFromSerialized squad.serialized @notes.val(squad.additional_data.notes ? '') @tag.val(squad.additional_data.tag ? '') @backend_status.fadeOut 'slow' @current_squad.dirty = false @container.trigger 'xwing-backend:squadDirtinessChanged' @container.trigger 'xwing-backend:squadNameChanged' onSquadDirtinessChanged: () => @current_squad.name = $.trim(@squad_name_input.val()) @backend_save_list_button.toggleClass 'disabled', not (@current_squad.dirty and @total_points > 0) @backend_save_list_as_button.toggleClass 'disabled', @total_points == 0 @backend_delete_list_button.toggleClass 'disabled', not @current_squad.id? if @ships.length > 1 $('meta[property="og:description"]').attr("content", "X-Wing Squadron by YASB 2.0: " + @current_squad.name + ": " + @describeSquad()) else $('meta[property="og:description"]').attr("content", "YASB 2.0 is a simple, fast, and easy to use squad builder for X-Wing Miniatures by Fantasy Flight Games.") # Moved XWS update to whenever the dirtyness changed rather than on points updated. @xws_textarea.val $.trim JSON.stringify(@toXWS()) $('#xws-qrcode-container').text '' $('#xws-qrcode-container').qrcode render: 'canvas' text: JSON.stringify(@toMinimalXWS()) ec: 'L' size: 128 onSquadNameChanged: () => if @current_squad.name.length > SQUAD_DISPLAY_NAME_MAX_LENGTH short_name = "#{@current_squad.name.substr(0, SQUAD_DISPLAY_NAME_MAX_LENGTH)}&hellip;" else short_name = @current_squad.name @squad_name_placeholder.text '' @squad_name_placeholder.append short_name @squad_name_input.val @current_squad.name return unless $.getParameterByName('f') == @faction if @current_squad.name != "Unnamed Squadron" and @current_squad.name != "Unsaved Squadron" if (document.title != "YASB 2.0 - " + @current_squad.name) document.title = "YASB 2.0 - " + @current_squad.name else document.title = "YASB 2.0" removeAllShips: -> while @ships.length > 0 @removeShip @ships[0] throw new Error("Ships not emptied") if @ships.length > 0 showTextListModal: -> # Display print/text view modal @list_modal.modal 'show' showXWSModal: (xws) -> # Display xws view modal @select_xws_view() @showTextListModal() showChooseObstaclesModal: -> @obstacles_select.val(@current_squad.additional_data.obstacles) @choose_obstacles_modal.modal 'show' showChooseObstaclesSelectImage: (obstacle) -> @image_name = 'images/' + obstacle + '.png' @obstacles_select_image.find('.obstacle-image').attr 'src', @image_name @obstacles_select_image.show() updateObstacleSelect: (obstacles) -> @current_obstacles = obstacles @obstacles_select.val(obstacles) serialize: -> serialization_version = 8 game_type_abbrev = switch @game_type_selector.val() when 'standard' 's' when 'hyperspace' 'h' when 'epic' 'e' when 'quickbuild' 'q' selected_points = $.trim @desired_points_input.val() """v#{serialization_version}Z#{game_type_abbrev}Z#{selected_points}Z#{( ship.toSerialized() for ship in @ships when ship.pilot? and (not @isQuickbuild or ship.primary) ).join 'Y'}""" changeGameTypeOnSquadLoad: (gametype) -> if @game_type_selector.val() != gametype $(window).trigger 'xwing:gameTypeChanged', gametype loadFromSerialized: (serialized) -> @suppress_automatic_new_ship = true # Clear all existing ships @removeAllShips() re = if "Z" in serialized then /^v(\d+)Z(.*)/ else /^v(\d+)!(.*)/ matches = re.exec serialized if matches? # versioned version = parseInt matches[1] # version 1-3 are 1st edition only (may be removed here) # version 4 is the final version of 1st edition x-wing, and has been the first few weeks of YASB 2.0 # version 5 is the first version for 2nd edtition x-wing only, it features extended (=standard), hyperspace, quickbuild and custom mode # version 6 has the only difference to version 5 is, that custom (=extended with != 200 points) has been removed and points are specified for all modes. # version 7 has arbitrary ordering of upgrades additionally supported # version 8 is the current version, replacing "!" with "Z" in the serialzed string, and 'Y' etc ship_splitter = if version > 7 then 'Y' else ';' # parse out game type [ game_type_abbrev, desired_points, serialized_ships ] = if version > 7 [g, p, s] = matches[2].split('Z') [g, parseInt(p), s] else [ game_type_and_point_abbrev, s ] = matches[2].split('!') if parseInt(game_type_and_point_abbrev.split('=')[1]) p = parseInt(game_type_and_point_abbrev.split('=')[1]) else p = 200 g = game_type_and_point_abbrev.split('=')[0] [ g, p, s ] # check if there are serialized ships to load if !serialized_ships? # something went wrong, we can't load that serialization @loading_failed_container.toggleClass 'd-none', false return switch game_type_abbrev when 's' @changeGameTypeOnSquadLoad 'standard' when 'h' @changeGameTypeOnSquadLoad 'hyperspace' when 'e' @changeGameTypeOnSquadLoad 'epic' when 'q' @changeGameTypeOnSquadLoad 'quickbuild' @desired_points_input.val desired_points @desired_points_input.change() ships_with_unmet_dependencies = [] if serialized_ships.length? for serialized_ship in serialized_ships.split(ship_splitter) unless serialized_ship == '' new_ship = @addShip() # try to create ship. fromSerialized returns false, if some upgrade have been skipped as they are not legal until now (e.g. 0-0-0 but vader is not yet in the squad) # if not the entire ship is valid, we'll try again later - but keep the valid part added, so other ships may already see some upgrades if (not new_ship.fromSerialized version, serialized_ship) or not new_ship.pilot # also check, if the pilot has been set (the pilot himself was not invalid) ships_with_unmet_dependencies.push [new_ship, serialized_ship] for ship in ships_with_unmet_dependencies # 2nd attempt to load ships with unmet dependencies. if not ship[0].pilot # create ship, if the ship was so invalid, that it in fact decided to not exist ship[0] = @addShip() ship[0].fromSerialized version, ship[1] @suppress_automatic_new_ship = false # Finally, the unassigned ship @addShip() select_xws_view: () -> @select_xws_view_button.blur() unless @list_display_mode == 'xws' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_xws_view_button.addClass 'btn-inverse' @list_display_mode = 'xws' @xws_container.show() @bbcode_container.hide() @htmlview_container.hide() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @fancy_container.hide() @tts_container.hide() @xws_textarea.select() @xws_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; uniqueIndex: (unique, type) -> if type not of @uniques_in_use throw new Error("Invalid unique type '#{type}'") @uniques_in_use[type].indexOf unique claimUnique: (unique, type, cb) => if @uniqueIndex(unique, type) < 0 # Claim pilots with the same canonical name for other in (exportObj.pilotsByUniqueName[unique.canonical_name.getXWSBaseName()] or []) if unique != other if @uniqueIndex(other, 'Pilot') < 0 # console.log "Also claiming unique pilot #{other.canonical_name} in use" @uniques_in_use['Pilot'].push other else throw new Error("Unique #{type} '#{unique.name}' already claimed as pilot") # Claim other upgrades with the same canonical name for otherslot, bycanonical of exportObj.upgradesBySlotUniqueName for canonical, other of bycanonical if canonical.getXWSBaseName() == unique.canonical_name.getXWSBaseName() and unique != other if @uniqueIndex(other, 'Upgrade') < 0 # console.log "Also claiming unique #{other.canonical_name} (#{otherslot}) in use" @uniques_in_use['Upgrade'].push other # else # throw new Error("Unique #{type} '#{unique.name}' already claimed as #{otherslot}") # Solitary Check if unique.solitary? @uniques_in_use['Slot'].push unique.slot @uniques_in_use[type].push unique else throw new Error("Unique #{type} '#{unique.name}' already claimed") cb() releaseUnique: (unique, type, cb) => idx = @uniqueIndex(unique, type) if idx >= 0 # Release all uniques with the same canonical name and base name for type, uniques of @uniques_in_use # Removing stuff in a loop sucks, so we'll construct a new list if type == 'Slot' if unique.solitary? @uniques_in_use[type] = [] for u in uniques if u != unique.slot # Keep this one @uniques_in_use[type].push u.slot else @uniques_in_use[type] = [] for u in uniques if u.canonical_name.getXWSBaseName() != unique.canonical_name.getXWSBaseName() # Keep this one @uniques_in_use[type].push u # else # console.log "Releasing #{u.name} (#{type}) with canonical name #{unique.canonical_name}" else throw new Error("Unique #{type} '#{unique.name}' not in use") cb() addShip: -> new_ship = new Ship builder: this container: @ship_container @ships.push new_ship @ship_number_invalid_container.toggleClass 'd-none', (@ships.length < 10 and @ships.length > 2) # bounds are 2..10 as we always have a "empty" ship at the bottom @multi_faction_warning_container.toggleClass 'd-none', (@faction != "All") new_ship removeShip: (ship, cb=$.noop) -> if ship?.destroy? await ship.destroy defer() await @container.trigger 'xwing:pointsUpdated', defer() @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' @ship_number_invalid_container.toggleClass 'd-none', (@ships.length < 10 and @ships.length > 2) @multi_faction_warning_container.toggleClass 'd-none', (@faction != "All") cb() matcher: (item, term) -> item.toUpperCase().indexOf(term.toUpperCase()) >= 0 isOurFaction: (faction, alt_faction = '') -> check_faction = @faction if @faction == "All" if alt_faction != '' check_faction = alt_faction else return true if faction instanceof Array for f in faction if getPrimaryFaction(f) == check_faction return true false else getPrimaryFaction(faction) == check_faction isItemAvailable: (item_data, shipCheck=false) -> # this method is not even invoked by most quickbuild stuff to check availability for quickbuild squads, as the method was formerly just telling apart extended/hyperspace if @isQuickbuild return true else if @isHyperspace return exportObj.hyperspaceCheck(item_data, @faction, shipCheck) else if (not @isEpic) return exportObj.epicExclusions(item_data) else return true getAvailableShipsMatching: (term='',sorted = true, collection_only = false) -> ships = [] for ship_name, ship_data of exportObj.ships if @isOurFaction(ship_data.factions) and (@matcher(ship_data.name, term) or (ship_data.display_name and @matcher(ship_data.display_name, term))) if (@isItemAvailable(ship_data, true)) if (not collection_only or (@collection? and (@collection.checks.collectioncheck == "true") and @collection.checkShelf('ship', ship_data.name))) ships.push id: ship_data.name text: if ship_data.display_name then ship_data.display_name else ship_data.name name: ship_data.name display_name: ship_data.display_name canonical_name: ship_data.canonical_name xws: ship_data.xws icon: if ship_data.icon then ship_data.icon else ship_data.xws if sorted ships.sort exportObj.sortHelper return ships getAvailableShipsMatchingAndCheapEnough: (points, term='', sorted=false, collection_only = false) -> # returns a list of ships that have at least one pilot cheaper than the given points value possible_ships = @getAvailableShipsMatching(term, sorted, collection_only) cheap_ships = [] for ship in possible_ships pilots = @getAvailablePilotsForShipIncluding(ship.name, null, '', true) if pilots.length and pilots[0].points <= points cheap_ships.push(ship) return cheap_ships getAvailablePilotsForShipIncluding: (ship, include_pilot, term='', sorted = true, ship_selector = null) -> # Returns data formatted for Select2 retval = [] if not @isQuickbuild # select available pilots according to ususal pilot selection available_faction_pilots = (pilot for pilot_name, pilot of exportObj.pilots when (not ship? or pilot.ship == ship) and @isOurFaction(pilot.faction) and (@matcher(pilot_name, term) or (pilot.display_name and @matcher(pilot.display_name, term)) ) and (@isItemAvailable(pilot, true))) eligible_faction_pilots = (pilot for pilot_name, pilot of available_faction_pilots when (not pilot.unique? or pilot not in @uniques_in_use['Pilot'] or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()) and (not pilot.max_per_squad? or @countPilots(pilot.canonical_name) < pilot.max_per_squad or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()) and (not pilot.restriction_func? or pilot.restriction_func((builder: @) , pilot))) # Re-add selected pilot if include_pilot? and include_pilot.unique? and (@matcher(include_pilot.name, term) or (include_pilot.display_name and @matcher(include_pilot.display_name, term)) ) eligible_faction_pilots.push include_pilot retval = ({ id: pilot.id, text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then pilot.skill + ' - ' else ''}#{if pilot.display_name then pilot.display_name else pilot.name} (#{pilot.points})", points: pilot.points, ship: pilot.ship, name: pilot.name, display_name: pilot.display_name, disabled: pilot not in eligible_faction_pilots } for pilot in available_faction_pilots) else # select according to quickbuild cards # filter for faction and ship quickbuilds_matching_ship_and_faction = (quickbuild for id, quickbuild of exportObj.quickbuildsById when (not ship? or quickbuild.ship == ship) and @isOurFaction(quickbuild.faction) and (@matcher(quickbuild.pilot, term) or (exportObj.pilots[quickbuild.pilot].display_name? and @matcher(exportObj.pilots[quickbuild.pilot].display_name, term)) )) # create a list of the uniques belonging to the currently selected pilot uniques_in_use_by_pilot_in_use = [] if include_pilot? and include_pilot != -1 include_quickbuild = exportObj.quickbuildsById[include_pilot] include_pilot_pilot = exportObj.pilots[include_quickbuild.pilot] if include_pilot_pilot.unique? uniques_in_use_by_pilot_in_use.push include_pilot_pilot for other in (exportObj.pilotsByUniqueName[include_pilot_pilot.canonical_name.getXWSBaseName()] or []) if other? uniques_in_use_by_pilot_in_use.push other for include_upgrade_name in include_quickbuild.upgrades ? [] include_upgrade = exportObj.upgrades[include_upgrade_name] if include_upgrade.unique? uniques_in_use_by_pilot_in_use.push other for other in (exportObj.pilotsByUniqueName[include_upgrade.canonical_name.getXWSBaseName()] or []) if other? uniques_in_use_by_pilot_in_use.push other if include_upgrade.solitary? uniques_in_use_by_pilot_in_use.push include_upgrade.slot # we should also add upgrades with the same unique name like some selected upgrades or the pilot. However, finding them is teadious # we should also add uniques used by a linked ship. however, while it is easy to allow selecting them, it is harder to properly add them - as one need to make sure the order of selecting ship + linked ship matters # filter for uniques in use allowed_quickbuilds_containing_uniques_in_use = [] loop: for id, quickbuild of quickbuilds_matching_ship_and_faction if exportObj.pilots[quickbuild.pilot]?.unique? and exportObj.pilots[quickbuild.pilot] in @uniques_in_use.Pilot and not (exportObj.pilots[quickbuild.pilot] in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id continue if exportObj.pilots[quickbuild.pilot]?.max_per_squad? and @countPilots(exportObj.pilots[quickbuild.pilot].canonical_name) >= exportObj.pilots[quickbuild.pilot].max_per_squad and not (exportObj.pilots[quickbuild.pilot] in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id continue if quickbuild.upgrades? for upgrade in quickbuild.upgrades upgradedata = exportObj.upgrades[upgrade] if not upgradedata? console.log("There was an Issue including the upgrade " + upgrade + " in some quickbuild. Please report that Issue!") continue if upgradedata.unique? and upgradedata in @uniques_in_use.Upgrade and not (upgradedata in uniques_in_use_by_pilot_in_use) # check, if unique is used by this ship or it's linked ship if ship_selector == null or not (upgrade in exportObj.quickbuildsById[ship_selector.quickbuildId].upgrades or (ship_selector.linkedShip and upgrade in (exportObj.quickbuildsById[ship_selector.linkedShip?.quickbuildId].upgrades ? []))) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id break # check if solitary type is already claimed if upgradedata.solitary? and upgradedata.slot in @uniques_in_use['Slot'] and not (upgradedata.slot in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id break retval = ({id: quickbuild.id, text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then exportObj.pilots[quickbuild.pilot].skill + ' - ' else ''}#{if exportObj.pilots[quickbuild.pilot].display_name then exportObj.pilots[quickbuild.pilot].display_name else quickbuild.pilot}#{quickbuild.suffix} (#{quickbuild.threat})", points: quickbuild.threat, ship: quickbuild.ship, disabled: quickbuild.id in allowed_quickbuilds_containing_uniques_in_use} for quickbuild in quickbuilds_matching_ship_and_faction) if sorted retval = retval.sort exportObj.sortHelper retval dfl_filter_func = -> true countUpgrades: (canonical_name) -> # returns number of upgrades with given canonical name equipped count = 0 for ship in @ships for upgrade in ship.upgrades if upgrade?.data?.canonical_name == canonical_name count++ count countPilots: (canonical_name) -> # returns number of pilots with given canonical name count = 0 for ship in @ships if ship?.pilot?.canonical_name.getXWSBaseName() == canonical_name.getXWSBaseName() count++ count isShip: (ship, name) -> # console.log "returning #{f} #{name}" if ship instanceof Array for f in ship if f == name return true false else ship == name getAvailableUpgradesIncluding: (slot, include_upgrade, ship, this_upgrade_obj, term='', filter_func=@dfl_filter_func, sorted=true) -> # Returns data formatted for Select2 upgrades_in_use = (upgrade.data for upgrade in ship.upgrades) available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgrades when exportObj.slotsMatching(upgrade.slot, slot) and ( @matcher(upgrade_name, term) or (upgrade.display_name and @matcher(upgrade.display_name, term)) ) and (not upgrade.ship? or @isShip(upgrade.ship, ship.data.name)) and (not upgrade.faction? or @isOurFaction(upgrade.faction, ship.pilot.faction)) and (@isItemAvailable(upgrade))) # available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgrades when exportObj.slotsMatching(upgrade.slot, slot) and ( @matcher(upgrade_name, term) or (upgrade.display_name and @matcher(upgrade.display_name, term)) ) and (not upgrade.ship? or @isShip(upgrade.ship, ship.data.name)) and (not upgrade.faction? or ((@faction != "All") and @isOurFaction(upgrade.faction)) or ((@faction == "All") and (not ship.pilot? or (ship.pilot.faction == upgrade.faction)))) and (@isItemAvailable(upgrade))) if filter_func != @dfl_filter_func available_upgrades = (upgrade for upgrade in available_upgrades when filter_func(upgrade)) eligible_upgrades = (upgrade for upgrade_name, upgrade of available_upgrades when (not upgrade.unique? or upgrade not in @uniques_in_use['Upgrade']) and (not (ship? and upgrade.restrictions?) or ship.restriction_check(upgrade.restrictions, this_upgrade_obj)) and upgrade not in upgrades_in_use and ((not upgrade.max_per_squad?) or ship.builder.countUpgrades(upgrade.canonical_name) < upgrade.max_per_squad) and (not upgrade.solitary? or (upgrade.slot not in @uniques_in_use['Slot'] or include_upgrade?.solitary?))) for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?) eligible_upgrades.removeItem equipped_upgrade # Re-enable selected upgrade if include_upgrade? and ((( @matcher(include_upgrade.name, term) or (include_upgrade.display_name and @matcher(include_upgrade.display_name, term))) ))# or current_upgrade_forcibly_removed) # available_upgrades.push include_upgrade eligible_upgrades.push include_upgrade retval = ({ id: upgrade.id, text: "#{if upgrade.display_name then upgrade.display_name else upgrade.name} (#{this_upgrade_obj.getPoints(upgrade)}#{if upgrade.pointsarray then '*' else ''})", points: this_upgrade_obj.getPoints(upgrade), name: upgrade.name, display_name: upgrade.display_name, disabled: upgrade not in eligible_upgrades } for upgrade in available_upgrades) if sorted retval = retval.sort exportObj.sortHelper # Possibly adjust the upgrade if this_upgrade_obj?adjustment_func? (this_upgrade_obj.adjustment_func(upgrade) for upgrade in retval) else retval getSquadDialsAsHTML: () -> dialHTML = "" added_dials = {} for ship in @ships if ship.pilot? # There is always one "empty" ship at the bottom of each squad, that we want to skip. maneuvers_unmodified = ship.data.maneuvers maneuvers_modified = ship.effectiveStats().maneuvers if not added_dials[ship.data.name]? or not (maneuvers_modified.toString() in added_dials[ship.data.name]) # we only want to add each dial once per ship (if two ships share a dial, add two copies of the dial) added_dials[ship.data.name] = (added_dials[ship.data.name] ? []).concat [maneuvers_modified.toString()] # save maneuver as string, as that is easier to compare than arrays (if e.g. two ships of same type, one with and one without R4 are in a squad, we add 2 dials) dialHTML += '<div class="fancy-dial">' + """<h4 class="ship-name-dial">#{if ship.data.display_name? then ship.data.display_name else ship.data.name}""" + """#{if maneuvers_modified.toString() != maneuvers_unmodified.toString() then " (upgraded)" else ""}</h4>""" + @getManeuverTableHTML(maneuvers_modified, maneuvers_unmodified) + '</div>' return """ <div class="print-dials-container"> #{dialHTML} </div> """ # dialHTML = @builder.getManeuverTableHTML(effective_stats.maneuvers, @data.maneuvers) # Converts a maneuver table for into an HTML table. getManeuverTableHTML: (maneuvers, baseManeuvers) -> if not maneuvers? or maneuvers.length == 0 return "Missing maneuver info." # Preprocess maneuvers to see which bearings are never used so we # don't render them. bearings_without_maneuvers = [0...maneuvers[0].length] for bearings in maneuvers for difficulty, bearing in bearings if difficulty > 0 bearings_without_maneuvers.removeItem bearing # console.log "bearings without maneuvers:" # console.dir bearings_without_maneuvers outTable = "<table><tbody>" for speed in [maneuvers.length - 1 .. 0] haveManeuver = false for v in maneuvers[speed] if v > 0 haveManeuver = true break continue if not haveManeuver outTable += "<tr><td>#{speed}</td>" for turn in [0 ... maneuvers[speed].length] continue if turn in bearings_without_maneuvers outTable += "<td>" if maneuvers[speed][turn] > 0 color = switch maneuvers[speed][turn] when 1 then "dodgerblue" when 2 then "white" when 3 then "red" when 4 then "purple" # we need this to change the color to b/w in case we want to print b/w maneuverClass = switch maneuvers[speed][turn] when 1 then "svg-blue-maneuver" when 2 then "svg-white-maneuver" when 3 then "svg-red-maneuver" when 4 then "svg-purple-maneuver" outTable += """<svg xmlns="http://www.w3.org/2000/svg" width="30px" height="30px" viewBox="0 0 200 200">""" outlineColor = "black" maneuverClass2 = "svg-base-maneuver" if maneuvers[speed][turn] != baseManeuvers[speed][turn] outlineColor = "DarkSlateGrey" # highlight manuevers modified by another card (e.g. R2 Astromech makes all 1 & 2 speed maneuvers green) maneuverClass2 = "svg-modified-maneuver" if speed == 0 and turn == 2 outTable += """<rect class="svg-maneuver-stop #{maneuverClass} #{maneuverClass2}" x="50" y="50" width="100" height="100" style="fill:#{color}" />""" else transform = "" className = "" switch turn when 0 # turn left linePath = "M160,180 L160,70 80,70" trianglePath = "M80,100 V40 L30,70 Z" when 1 # bank left linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(-5 -15) rotate(45 70 90)' " when 2 # straight linePath = "M100,180 L100,100 100,80" trianglePath = "M70,80 H130 L100,30 Z" when 3 # bank right linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(5 -15) rotate(-45 130 90)' " when 4 # turn right linePath = "M40,180 L40,70 120,70" trianglePath = "M120,100 V40 L170,70 Z" when 5 # k-turn/u-turn linePath = "M50,180 L50,100 C50,10 140,10 140,100 L140,120" trianglePath = "M170,120 H110 L140,180 Z" when 6 # segnor's loop left linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(0 50)'" when 7 # segnor's loop right linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(0 50)'" when 8 # tallon roll left linePath = "M160,180 L160,70 80,70" trianglePath = "M60,100 H100 L80,140 Z" when 9 # tallon roll right linePath = "M40,180 L40,70 120,70" trianglePath = "M100,100 H140 L120,140 Z" when 10 # backward left linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(5 -15) rotate(-45 130 90)' " className = 'backwards' when 11 # backward straight linePath = "M100,180 L100,100 100,80" trianglePath = "M70,80 H130 L100,30 Z" className = 'backwards' when 12 # backward right linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(-5 -15) rotate(45 70 90)' " className = 'backwards' outTable += $.trim """ <g class="maneuver #{className}"> <path class = 'svg-maneuver-outer #{maneuverClass} #{maneuverClass2}' stroke-width='25' fill='none' stroke='#{outlineColor}' d='#{linePath}' /> <path class = 'svg-maneuver-triangle #{maneuverClass} #{maneuverClass2}' d='#{trianglePath}' fill='#{color}' stroke-width='5' stroke='#{outlineColor}' #{transform}/> <path class = 'svg-maneuver-inner #{maneuverClass} #{maneuverClass2}' stroke-width='15' fill='none' stroke='#{color}' d='#{linePath}' /> </g> """ outTable += "</svg>" outTable += "</td>" outTable += "</tr>" outTable += "</tbody></table>" outTable formatActions: (actions,seperation,keyword=[]) -> action_icons = [] for action in actions color = "" prefix = seperation if "Droid" in keyword action = action.replace('Focus', 'Calculate') # Search and filter each type of action by its prefix and then reformat it for html if action.search('> ') != -1 action = action.replace(/> /gi, '') prefix = """ <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> """ if action.search('F-') != -1 color = "force " action = action.replace(/F-/gi, '') else if action.search('R-') != -1 color = "red " action = action.replace(/R-/gi, '') action = action.toLowerCase().replace(/[^0-9a-z]/gi, '') action_icons.push """#{prefix}<i class="xwing-miniatures-font #{color}xwing-miniatures-font-#{action}"></i>""" actionlist = action_icons.join '' return actionlist.replace(seperation,'') showTooltip: (type, data, additional_opts, container = @info_container, force_update = false) -> if data != @tooltip_currently_displaying or force_update switch type when 'Ship' # we get all pilots for the ship, to display stuff like available slots which are treated as pilot properties, not ship properties (which makes sense, as they depend on the pilot, e.g. talent or force slots) possible_inis = [] slot_types = {} # one number per slot: 0: not available for that ship. 1: always available for that ship. 2: available for some pilots on that ship. 3: slot two times availabel for that ship 4: slot one or two times available (depending on pilot) 5: slot zero to two times available 6: slot three times available (no mixed-case implemented) -1: undefined for slot of exportObj.upgradesBySlotCanonicalName slot_types[slot] = -1 for name, pilot of exportObj.pilots if pilot.ship != data.name continue if not (pilot.skill in possible_inis) possible_inis.push(pilot.skill) for slot, state of slot_types switch pilot.slots.filter((item) => item == slot).length when 1 switch state when -1 slot_types[slot] = 1 when 0 slot_types[slot] = 2 when 3 slot_types[slot] = 4 when 0 switch state when -1 slot_types[slot] = 0 when 1 slot_types[slot] = 2 when 3,4 slot_types[slot] = 5 when 2 switch state when -1 slot_types[slot] = 3 when 0,2 slot_types[slot] = 5 when 1 slot_types[slot] = 4 when 3 slot_types[slot] = 6 possible_inis.sort() container.find('.info-type').text type container.find('.info-name').html """#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" if @collection?.counts? ship_count = @collection.counts?.ship?[data.name] ? 0 container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() first = true inis = String(possible_inis[0]) for ini in possible_inis if not first inis += ", " + ini first = false container.find('tr.info-skill td.info-data').text inis container.find('tr.info-skill').show() container.find('tr.info-engagement').hide() container.find('tr.info-attack td.info-data').text(data.attack) container.find('tr.info-attack-bullseye td.info-data').text(data.attackbull) container.find('tr.info-attack-fullfront td.info-data').text(data.attackf) container.find('tr.info-attack-left td.info-data').text(data.attackl) container.find('tr.info-attack-right td.info-data').text(data.attackr) container.find('tr.info-attack-back td.info-data').text(data.attackb) container.find('tr.info-attack-turret td.info-data').text(data.attackt) container.find('tr.info-attack-doubleturret td.info-data').text(data.attackdt) container.find('tr.info-attack').toggle(data.attack?) container.find('tr.info-attack-bullseye').toggle(data.attackbull?) container.find('tr.info-attack-fullfront').toggle(data.attackf?) container.find('tr.info-attack-left').toggle(data.attackl?) container.find('tr.info-attack-right').toggle(data.attackr?) container.find('tr.info-attack-back').toggle(data.attackb?) container.find('tr.info-attack-turret').toggle(data.attackt?) container.find('tr.info-attack-doubleturret').toggle(data.attackdt?) container.find('tr.info-ship').hide() if data.large? container.find('tr.info-base td.info-data').text "Large" else if data.medium? container.find('tr.info-base td.info-data').text "Medium" else if data.huge? container.find('tr.info-base td.info-data').text "Huge" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(data.attack_icon ? 'xwing-miniatures-font-attack') container.find('tr.info-range').hide() container.find('tr.info-agility td.info-data').text(data.agility) container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text(data.hull) container.find('tr.info-hull').show() recurringicon = '' if data.shieldrecurr? count = 0 while count < data.shieldrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-shields td.info-data').html (data.shields + recurringicon) container.find('tr.info-shields').show() recurringicon = '' if data.energyrecurr? count = 0 while count < data.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-energy td.info-data').html (data.energy + recurringicon) container.find('tr.info-energy').toggle(data.energy?) # One may want to check for force sensitive pilots and display the possible values here (like done for ini), but I'll skip this for now. container.find('tr.info-force').hide() container.find('tr.info-charge').hide() container.find('tr.info-actions td.info-data').html @formatActions(data.actions, ", ", data.keyword ? []) container.find('tr.info-actions').show() # Display all available slots, put brackets around slots that are only available for some pilots container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html(((if state == 1 then exportObj.translate(@language, 'sloticon', slot) else (if state == 2 then '('+exportObj.translate(@language, 'sloticon', slot)+')' else (if state == 3 then (exportObj.translate(@language, 'sloticon', slot) + exportObj.translate(@language, 'sloticon', slot)) else (if state == 4 then (exportObj.translate(@language, 'sloticon', slot) + '(' + exportObj.translate(@language, 'sloticon', slot) + ')') else (if state == 5 then ('(' + exportObj.translate(@language, 'sloticon', slot) + exportObj.translate(@language, 'sloticon', slot) + ')') else (if state == 6 then (exportObj.translate(@language, 'sloticon',slot) + exportObj.translate(@language, 'sloticon',slot) + exportObj.translate(@language, 'sloticon',slot)))))))) for slot, state of slot_types).join(' ') or 'None') container.find('p.info-text').hide() container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(data.maneuvers, data.maneuvers)) sources = (exportObj.translate(@language, 'sources', source) for source in data.sources).sort() container.find('.info-sources.info-data').text if (sources.length > 1) or (not ('Loose Ships' in sources)) then (if sources.length > 0 then sources.join(', ') else exportObj.translate(@language, 'ui', 'unreleased')) else "Only available from 1st edition" container.find('.info-sources').show() when 'Pilot' container.find('.info-type').text type container.find('.info-sources.info-data').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') container.find('.info-sources').show() if @collection?.counts? pilot_count = @collection.counts?.pilot?[data.name] ? 0 ship_count = @collection.counts.ship?[data.ship] ? 0 container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() # if the pilot is already selected and has uprades, some stats may be modified if additional_opts?.effectiveStats? effective_stats = additional_opts.effectiveStats() #logic to determine how many dots to use for uniqueness if data.unique? uniquedots = "&middot;&nbsp;" else if data.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" container.find('.info-name').html """#{uniquedots}#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" restriction_info = @restriction_text(data) + @upgrade_effect(data) if restriction_info != '' container.find('p.info-restrictions').html restriction_info ? '' container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html data.text ? '' container.find('p.info-text').show() ship = exportObj.ships[data.ship] container.find('tr.info-ship td.info-data').text data.ship container.find('tr.info-ship').show() if ship.large? container.find('tr.info-base td.info-data').text "Large" else if ship.medium? container.find('tr.info-base td.info-data').text "Medium" else if ship.huge? container.find('tr.info-base td.info-data').text "Huge" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() container.find('tr.info-skill td.info-data').text data.skill container.find('tr.info-skill').show() if data.engagement? container.find('tr.info-engagement td.info-data').text data.engagement container.find('tr.info-engagement').show() else container.find('tr.info-engagement').hide() # for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList # container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-attack') container.find('tr.info-attack td.info-data').text statAndEffectiveStat((data.ship_override?.attack ? ship.attack), effective_stats, 'attack') container.find('tr.info-attack').toggle(ship.attack? or effective_stats?.attack?) container.find('tr.info-attack-fullfront td.info-data').text statAndEffectiveStat((data.ship_override?.attackf ? ship.attackf), effective_stats, 'attackf') container.find('tr.info-attack-fullfront').toggle(ship.attackf? or effective_stats?.attackf?) container.find('tr.info-attack-bullseye td.info-data').text statAndEffectiveStat((data.ship_override?.attackbull ? ship.attackbull), effective_stats, 'attackbull') container.find('tr.info-attack-bullseye').toggle(ship.attackbull? or effective_stats?.attackbull?) container.find('tr.info-attack-left td.info-data').text statAndEffectiveStat((data.ship_override?.attackl ? ship.attackl), effective_stats, 'attackl') container.find('tr.info-attack-left').toggle(ship.attackl? or effective_stats?.attackl?) container.find('tr.info-attack-right td.info-data').text statAndEffectiveStat((data.ship_override?.attackr ? ship.attackr), effective_stats, 'attackr') container.find('tr.info-attack-right').toggle(ship.attackr? or effective_stats?.attackr?) container.find('tr.info-attack-back td.info-data').text statAndEffectiveStat((data.ship_override?.attackb ? ship.attackb), effective_stats, 'attackb') container.find('tr.info-attack-back').toggle(ship.attackb? or effective_stats?.attackb?) container.find('tr.info-attack-turret td.info-data').text statAndEffectiveStat((data.ship_override?.attackt ? ship.attackt), effective_stats, 'attackt') container.find('tr.info-attack-turret').toggle(ship.attackt? or effective_stats?.attackt?) container.find('tr.info-attack-doubleturret td.info-data').text statAndEffectiveStat((data.ship_override?.attackdt ? ship.attackdt), effective_stats, 'attackdt') container.find('tr.info-attack-doubleturret').toggle(ship.attackdt? or effective_stats?.attackdt?) container.find('tr.info-range').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-agility td.info-data').text statAndEffectiveStat((data.ship_override?.agility ? ship.agility), effective_stats, 'agility') container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text statAndEffectiveStat((data.ship_override?.hull ? ship.hull), effective_stats, 'hull') container.find('tr.info-hull').show() recurringicon = '' if ship.shieldrecurr? count = 0 while count < ship.shieldrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-shields td.info-data').html (statAndEffectiveStat((data.ship_override?.shields ? ship.shields), effective_stats, 'shields') + recurringicon) container.find('tr.info-shields').show() recurringicon = '' if ship.energyrecurr? count = 0 while count < ship.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-energy td.info-data').html (statAndEffectiveStat((data.ship_override?.energy ? ship.energy), effective_stats, 'energy') + recurringicon) container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?) if (effective_stats?.force? and effective_stats.force > 0) or data.force? container.find('tr.info-force td.info-data').html (statAndEffectiveStat((data.ship_override?.force ? data.force), effective_stats, 'force') + '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').show() else container.find('tr.info-force').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').show() else container.find('tr.info-charge').hide() if effective_stats?.actions? container.find('tr.info-actions td.info-data').html @formatActions(data.ship_override?.actions ? effective_stats.actions, ", ") else container.find('tr.info-actions td.info-data').html @formatActions(data.ship_override?.actions ? ship.actions, ", ", data.keyword ? []) container.find('tr.info-actions').show() if @isQuickbuild container.find('tr.info-upgrades').hide() else container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html((exportObj.translate(@language, 'sloticon', slot) for slot in data.slots).join(' ') or 'None') container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(effective_stats?.maneuvers ? ship.maneuvers, ship.maneuvers)) when 'Quickbuild' container.find('.info-type').text 'Quickbuild' container.find('.info-sources').hide() # there are different sources for the pilot and the upgrade cards, so we won't display any container.find('.info-collection').hide() # same here, hard to give a single number telling a user how often he ownes all required cards pilot = exportObj.pilots[data.pilot] ship = exportObj.ships[data.ship] #logic to determine how many dots to use for uniqueness if pilot.unique? uniquedots = "&middot;&nbsp;" else if pilot.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" container.find('.info-name').html """#{uniquedots}#{if pilot.display_name then pilot.display_name else pilot.name}#{if data.suffix? then data.suffix else ""}#{if exportObj.isReleased(pilot) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" restriction_info = @restriction_text(data) + @upgrade_effect(data) if restriction_info != '' container.find('p.info-restrictions').html restriction_info ? '' container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html pilot.text ? '' container.find('p.info-text').show() container.find('tr.info-ship td.info-data').text data.ship container.find('tr.info-ship').show() if ship.large? container.find('tr.info-base td.info-data').text "Large" else if ship.medium? container.find('tr.info-base td.info-data').text "Medium" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() container.find('tr.info-skill td.info-data').text pilot.skill container.find('tr.info-skill').show() container.find('tr.info-engagement td.info-data').text pilot.skill container.find('tr.info-engagement').show() container.find('tr.info-attack td.info-data').text(pilot.ship_override?.attack ? ship.attack) container.find('tr.info-attack').toggle(pilot.ship_override?.attack? or ship.attack?) container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf) container.find('tr.info-attack-fullfront').toggle(ship.attackf?) container.find('tr.info-attack-bullseye td.info-data').text(ship.attackbull) container.find('tr.info-attack-bullseye').toggle(ship.attackbull?) container.find('tr.info-attack-left td.info-data').text(ship.attackl) container.find('tr.info-attack-left').toggle(ship.attackl?) container.find('tr.info-attack-right td.info-data').text(ship.attackr) container.find('tr.info-attack-right').toggle(ship.attackr?) container.find('tr.info-attack-back td.info-data').text(ship.attackb?) container.find('tr.info-attack-back').toggle(ship.attackb?) container.find('tr.info-attack-turret td.info-data').text(ship.attackt?) container.find('tr.info-attack-turret').toggle(ship.attackt?) container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt) container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?) # for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList # container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-frontarc') container.find('tr.info-energy td.info-data').text(pilot.ship_override?.energy ? ship.energy) container.find('tr.info-energy').toggle(pilot.ship_override?.energy? or ship.energy?) container.find('tr.info-range').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-agility td.info-data').text(pilot.ship_override?.agility ? ship.agility) container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text(pilot.ship_override?.hull ? ship.hull) container.find('tr.info-hull').show() container.find('tr.info-shields td.info-data').text(pilot.ship_override?.shields ? ship.shields) container.find('tr.info-shields').show() if effective_stats?.force? or data.force? container.find('tr.info-force td.info-data').html ((pilot.ship_override?.force ? pilot.force)+ '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').show() else container.find('tr.info-force').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').show() else container.find('tr.info-charge').hide() container.find('tr.info-actions td.info-data').html @formatActions(pilot.ship_override?.actions ? exportObj.ships[data.ship].actions, ", ", pilot.keyword ? []) container.find('tr.info-actions').show() container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html(((if exportObj.upgrades[upgrade].display_name? then exportObj.upgrades[upgrade].display_name else upgrade) for upgrade in (data.upgrades ? [])).join(', ') or 'None') container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(ship.maneuvers, ship.maneuvers)) when 'Addon' container.find('.info-type').text additional_opts.addon_type container.find('.info-sources.info-data').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') container.find('.info-sources').show() #logic to determine how many dots to use for uniqueness if data.unique? uniquedots = "&middot;&nbsp;" else if data.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" if @collection?.counts? addon_count = @collection.counts?['upgrade']?[data.name] ? 0 container.find('.info-collection').text """You have #{addon_count} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() container.find('.info-name').html """#{uniquedots}#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" if data.pointsarray? point_info = "<i><b>Point cost:</b> " + data.pointsarray + " when " if data.variableagility? and data.variableagility point_info += "agility is " + [0..data.pointsarray.length-1] else if data.variableinit? and data.variableinit point_info += "initiative is " + [0..data.pointsarray.length-1] else if data.variablebase? and data.variablebase point_info += " base size is small, medium, large or huge" point_info += "</i>" restriction_info = @restriction_text(data) + @upgrade_effect(data) if point_info? or (restriction_info != '') if point_info? and (restriction_info != '') point_info += "<br/>" container.find('p.info-restrictions').html (point_info ? '') + restriction_info container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html (data.text ? '') container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-engagement').hide() if data.energy? container.find('tr.info-energy td.info-data').text data.energy container.find('tr.info-energy').show() else container.find('tr.info-energy').hide() if data.attack? container.find('tr.info-attack td.info-data').text data.attack container.find('tr.info-attack').show() else container.find('tr.info-attack').hide() if data.attackt? container.find('tr.info-attack-turret td.info-data').text data.attackt container.find('tr.info-attack-turret').show() else container.find('tr.info-attack-turret').hide() if data.attackr? container.find('tr.info-attack-right td.info-data').text data.attackr container.find('tr.info-attack-right').show() else container.find('tr.info-attack-right').hide() if data.attackl? container.find('tr.info-attack-left td.info-data').text data.attackl container.find('tr.info-attack-left').show() else container.find('tr.info-attack-right').hide() if data.attackdt? container.find('tr.info-attack-doubleturret td.info-data').text data.attackdt container.find('tr.info-attack-doubleturret').show() else container.find('tr.info-attack-doubleturret').hide() if data.attackbull? container.find('tr.info-attack-bullseye td.info-data').text data.attackbull container.find('tr.info-attack-bullseye').show() else container.find('tr.info-attack-bullseye').hide() if data.attackf? container.find('tr.info-attack-fullfront td.info-data').text data.attackf container.find('tr.info-attack-fullfront').show() else container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-right').hide() container.find('tr.info-attack-left').hide() container.find('tr.info-attack-back').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').toggle(data.charge?) if data.range? container.find('tr.info-range td.info-data').text data.range container.find('tr.info-range').show() else container.find('tr.info-range').hide() if data.rangebonus? container.find('td.info-rangebonus').show() else container.find('td.info-rangebonus').hide() container.find('tr.info-force td.info-data').html (data.force + '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').toggle(data.force?) container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() when 'Rules' container.find('.info-type').hide() container.find('.info-sources').hide() container.find('.info-collection').hide() container.find('.info-name').html data.name container.find('.info-name').show() container.find('p.info-restrictions').hide() container.find('p.info-text').html data.text container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() container.find('tr.info-energy').hide() container.find('tr.info-attack').hide() container.find('tr.info-attack-turret').hide() container.find('tr.info-attack-bullseye').hide() container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-back').hide() container.find('tr.info-attack-doubleturret').hide() container.find('tr.info-charge').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-range').hide() container.find('tr.info-force').hide() when 'MissingStuff' container.find('.info-type').text "List of Missing items" container.find('.info-sources').hide() container.find('.info-collection').hide() container.find('.info-name').html "Missing items" container.find('.info-name').show() missingStuffInfoText = "To field this squad you need the following additional items: <ul>" for item in data missingStuffInfoText += """<li><strong>#{(if item.display_name? then item.display_name else item.name)}</strong> (""" first = true for source in item.sources if not first missingStuffInfoText += ", " missingStuffInfoText += source first = false missingStuffInfoText += ")</li>" missingStuffInfoText +="</ul>" container.find('p.info-restrictions').hide() container.find('p.info-text').html missingStuffInfoText container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() container.find('tr.info-energy').hide() container.find('tr.info-attack').hide() container.find('tr.info-attack-turret').hide() container.find('tr.info-attack-bullseye').hide() container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-back').hide() container.find('tr.info-attack-doubleturret').hide() container.find('tr.info-charge').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-range').hide() container.find('tr.info-force').hide() if container != @mobile_tooltip_modal container.show() @tooltip_currently_displaying = data # fix card viewer to view, if it is fully visible (it might not be e.g. on mobile devices. In that case keep it on its static position, so you can scroll to see it) if $(window).width() >= 768 well = container.find('.info-well') if $.isElementInView(well, true) well.css('position','fixed') else well.css('position','static') _randomizerLoopBody: (data) => if data.keep_running #console.log "Current points: #{@total_points} of #{data.max_points}, iteration=#{data.iterations} of #{data.max_iterations}, keep_running=#{data.keep_running}" if data.max_points - @total_points <= data.bid_goal and @total_points <= data.max_points # Hit bid range #console.log "Points reached exactly" data.keep_running = false else if @total_points < data.max_points #console.log "Need to add something" # Add something # Possible options: ship or empty addon slot unused_addons = [] for ship in @ships for upgrade in ship.upgrades unused_addons.push upgrade unless upgrade.data? or (upgrade.occupied_by? and upgrade.occupied_by != null) # 0 is ship, otherwise addon idx = $.randomInt(data.ships_or_upgrades + unused_addons.length) if idx < data.ships_or_upgrades or unused_addons.length == 0 # Add random ship #console.log "Add ship" available_ships = @getAvailableShipsMatchingAndCheapEnough(data.max_points - @total_points, '', false, data.collection_only) if available_ships.length == 0 if unused_addons.length > 0 idx = $.randomInt(unused_addons.length) + data.ships_or_upgrades else available_ships = @getAvailableShipsMatching('', false, data.collection_only) if (available_ships.length > 0) and ((@ships.length < data.ship_limit) or (data.ship_limit == 0)) ship_type = available_ships[$.randomInt available_ships.length].name available_pilots = @getAvailablePilotsForShipIncluding(ship_type) if available_pilots.length == 0 # edge case: It might have been a ship selected, that has only unique pilots - which all have been already selected return pilot = available_pilots[$.randomInt available_pilots.length] if not pilot.disabled and (if @isQuickbuild then exportObj.pilots[exportObj.quickbuildsById[pilot.id].pilot] else exportObj.pilotsById[pilot.id]).sources.intersects(data.allowed_sources) and ((not data.collection_only) or @collection.checkShelf('pilot', (if @isQuickbuild then exportObj.quickbuildsById[pilot.id] else pilot.name))) new_ship = @addShip() new_ship.setPilotById pilot.id if idx >= data.ships_or_upgrades and unused_addons.length != 0 # Add upgrade #console.log "Add addon" addon = unused_addons[idx - data.ships_or_upgrades] switch addon.type when 'Upgrade' available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship, addon,'', @dfl_filter_func, sorted = false) when (exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources) and ((not data.collection_only) or @collection.checkShelf('upgrade', upgrade.name)))) upgrade = if available_upgrades.length > 0 then available_upgrades[$.randomInt available_upgrades.length] else undefined if upgrade and not upgrade.disabled addon.setById upgrade.id else throw new Error("Invalid addon type #{addon.type}") else #console.log "Need to remove something" # Remove something removable_things = [] for ship in @ships for _ in [0...(11-data.ships_or_upgrades)] removable_things.push ship for upgrade in ship.upgrades removable_things.push upgrade if upgrade.data? if removable_things.length > 0 thing_to_remove = removable_things[$.randomInt removable_things.length] #console.log "Removing #{thing_to_remove}" if thing_to_remove instanceof Ship @removeShip thing_to_remove else if thing_to_remove instanceof GenericAddon thing_to_remove.setData null else throw new Error("Unknown thing to remove #{thing_to_remove}") # continue the "loop" window.setTimeout @_makeRandomizerLoopFunc(data), 0 else #console.log "Clearing timer #{data.timer}, iterations=#{data.iterations}, keep_running=#{data.keep_running}" # we have to stop randomizing, but should do a final check on our point costs. while @total_points > data.max_points removable_things = [] for ship in @ships # removable_things.push ship for upgrade in ship.upgrades removable_things.push upgrade if upgrade.data? if removable_things.length == 0 for ship in @ships removable_things.push ship if removable_things.length > 0 thing_to_remove = removable_things[$.randomInt removable_things.length] #console.log "Removing #{thing_to_remove}" if thing_to_remove instanceof Ship @removeShip thing_to_remove else if thing_to_remove instanceof GenericAddon thing_to_remove.setData null else throw new Error("Unknown thing to remove #{thing_to_remove}") if data.fill_zero_pts for ship in @ships for addon in ship.upgrades continue unless not (addon.data? or (addon.occupied_by? and addon.occupied_by != null)) available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship, addon,'', @dfl_filter_func, sorted = false) when (exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources) and (upgrade.points < 1) and ((not data.collection_only) or @collection.checkShelf('upgrade', upgrade.name)))) upgrade = if available_upgrades.length > 0 then available_upgrades[$.randomInt available_upgrades.length] else undefined if upgrade and not upgrade.disabled addon.setById upgrade.id window.clearTimeout data.timer # Update all selectors for ship in @ships ship.updateSelections() @suppress_automatic_new_ship = false @addShip() _makeRandomizerLoopFunc: (data) => () => @_randomizerLoopBody(data) randomSquad: (max_points=200, allowed_sources=null, timeout_ms=1000, bid_goal=5, ship_limit=0, ships_or_upgrades=3, collection_only=true, fill_zero_pts=false) -> @backend_status.fadeOut 'slow' @suppress_automatic_new_ship = true if allowed_sources.length < 1 allowed_sources = null # Clear all existing ships while @ships.length > 0 @removeShip @ships[0] throw new Error("Ships not emptied") if @ships.length > 0 data = max_points: max_points bid_goal: bid_goal ship_limit: ship_limit ships_or_upgrades: ships_or_upgrades keep_running: true allowed_sources: allowed_sources ? exportObj.expansions collection_only: @collection? and (@collection.checks.collectioncheck == "true") and collection_only fill_zero_pts: fill_zero_pts stopHandler = () => #console.log "*** TIMEOUT *** TIMEOUT *** TIMEOUT ***" data.keep_running = false data.timer = window.setTimeout stopHandler , timeout_ms #console.log "Timer set for #{timeout_ms}ms, timer is #{data.timer}" window.setTimeout @_makeRandomizerLoopFunc(data), 0 @resetCurrentSquad() @current_squad.name = '<NAME>' @container.trigger 'xwing-backend:squadNameChanged' setBackend: (backend) -> @backend = backend if @waiting_for_backend? for meth in @waiting_for_backend meth() upgrade_effect: (card) -> removestext = text = comma = '' if card.modifier_func statchange = attack: 0 attackf: 0 attackbull: 0 attackb: 0 attackt: 0 attackl: 0 attackr: 0 attackdt: 0 energy: 0 agility: 0 hull: 0 shields: 0 force: 0 actions: [] maneuvers: [0, 0] card.modifier_func(statchange) if statchange.attack != 0 text += comma + "%FRONTARC% (#{statchange.attack})" comma = ', ' if statchange.attackf != 0 text += comma + "%FULLFRONTARC% (#{statchange.attackf})" comma = ', ' if statchange.attackbull != 0 text += comma + "%BULLSEYEARC% (#{statchange.attackbull})" comma = ', ' if statchange.attackb != 0 text += comma + "%REARARC% (#{statchange.attackb})" comma = ', ' if statchange.attackt != 0 text += comma + "%SINGLETURRETARC% (#{statchange.attackt})" comma = ', ' if statchange.attackl != 0 text += comma + "%LEFTARC% (#{statchange.attackl})" comma = ', ' if statchange.attackr != 0 text += comma + "%RIGHTARC% (#{statchange.attackr})" comma = ', ' if statchange.attackdt != 0 text += comma + "%DOUBLETURRETARC% (#{statchange.attackdt})" comma = ', ' if statchange.energy != 0 text += comma + "%ENERGY% (#{statchange.energy})" comma = ', ' if statchange.agility != 0 text += comma + "%AGILITY% (#{statchange.agility})" comma = ', ' if statchange.hull != 0 text += comma + "%HULL% (#{statchange.hull})" comma = ', ' if statchange.shields != 0 text += comma + "%SHIELD% (#{statchange.shields})" comma = ', ' if statchange.actions.length > 0 text += comma + @formatActions(statchange.actions, ", ") comma = ', ' if card.confersAddons for addonname in card.confersAddons text += comma + "%#{addonname.slot.toUpperCase().replace(/[^a-z0-9]/gi, '')}%" comma = ', ' if card.unequips_upgrades comma = '' for slot in card.unequips_upgrades removestext += comma + "%#{slot.toUpperCase().replace(/[^a-z0-9]/gi, '')}%" comma = ', ' if text != '' data = text: "</br><b>Adds:</b> #{text}" if removestext != '' data.text += "</br><b>Removes:</b> #{removestext}" return exportObj.fixIcons(data) else return '' restriction_text: (card) -> uniquetext = comma = othertext = text = '' if card.restrictions for r in card.restrictions if r[0] == "orUnique" uniquetext = exportObj.translate(@language, 'restrictions', " or Squad Including") + " #{r[1]}" continue switch r[0] when "Base" text += comma + "#{r[1]} " + exportObj.translate(@language, 'restrictions', "Ship") when "Action" array = [r[1]] text += comma + @formatActions(array,"", []) when "Equipped" text += comma + "%#{r[1].toUpperCase().replace(/[^a-z0-9]/gi, '')}% Equipped" when "Slot" text += comma + exportObj.translate(@language, 'restrictions', "Extra") + " %#{r[1].toUpperCase().replace(/[^a-z0-9]/gi, '')}%" when "Keyword" text += comma + exportObj.translate(@language, 'restrictions', "#{r[1]}") when "AttackArc" text += comma + "%REARARC%" when "ShieldsGreaterThan" text += comma + "%SHIELD% > #{r[1]}" when "EnergyGreatterThan" text += comma + "%ENERGY% > #{r[1]}" when "InitiativeGreaterThan" text += comma + exportObj.translate(@language, 'restrictions', "Initiative") + " > #{r[1]}" when "InitiativeLessThan" text += comma + exportObj.translate(@language, 'restrictions', "Initiative")+ " < #{r[1]}" when "AgilityEquals" text += comma + exportObj.translate(@language, 'restrictions', "Agility") + " = #{r[1]}" when "isUnique" if r[1] == true text += comma + exportObj.translate(@language, 'restrictions', "Limited") else text += comma + exportObj.translate(@language, 'restrictions', "Non-Limited") when "Format" text += comma + exportObj.translate(@language, 'restrictions', "#{r[1]} Ship") when "Faction" othertext += comma + exportObj.translate(@language, 'faction', "#{r[1]}") comma = ', ' if not card.skill if othertext == '' if card.faction if card.faction instanceof Array for factionitem in card.faction othertext += comma + exportObj.translate(@language, 'faction', "#{factionitem}") comma = ' or ' else othertext += comma + exportObj.translate(@language, 'faction', "#{card.faction}") comma = ', ' if card.ship if card.ship instanceof Array for shipname in card.ship othertext += comma + shipname comma = ' or ' else othertext += comma + card.ship comma = ', ' if card.solitary othertext += comma + exportObj.translate(@language, 'faction', "Solitary") comma = ', ' if card.standardized othertext += comma + exportObj.translate(@language, 'faction', "Standardized") comma = ', ' text += othertext + uniquetext if text != '' data = text: "<i><b>" + exportObj.translate(@language, 'restrictions', "Restrictions") + ":</b> " + text + "</i>" return exportObj.fixIcons(data) else return '' describeSquad: -> if @getNotes().trim() == '' then ((ship.pilot.name for ship in @ships when ship.pilot?).join ', ') else @getNotes() listCards: -> card_obj = {} for ship in @ships if ship.pilot? card_obj[ship.pilot.name] = null for upgrade in ship.upgrades card_obj[upgrade.data.name] = null if upgrade.data? return Object.keys(card_obj).sort() getNotes: -> @notes.val() getTag: -> @tag.val() getObstacles: -> @current_obstacles isSquadPossibleWithCollection: -> # If the collection is uninitialized or empty, don't actually check it. if Object.keys(@collection?.expansions ? {}).length == 0 # console.log "collection not ready or is empty" return [true, []] else if @collection?.checks.collectioncheck != "true" # console.log "collection check not enabled" return [true, []] @collection.reset() validity = true missingStuff = [] for ship in @ships if ship.pilot? # Try to get both the physical model and the pilot card. ship_is_available = @collection.use('ship', ship.pilot.ship) pilot_is_available = @collection.use('pilot', ship.pilot.name) # console.log "#{@faction}: Ship #{ship.pilot.ship} available: #{ship_is_available}" # console.log "#{@faction}: Pilot #{ship.pilot.name} available: #{pilot_is_available}" validity = false unless ship_is_available and pilot_is_available missingStuff.push ship.data unless ship_is_available missingStuff.push ship.pilot unless pilot_is_available for upgrade in ship.upgrades if upgrade.data? upgrade_is_available = @collection.use('upgrade', upgrade.data.name) # console.log "#{@faction}: Upgrade #{upgrade.data.name} available: #{upgrade_is_available}" validity = false unless upgrade_is_available missingStuff.push upgrade.data unless upgrade_is_available [validity, missingStuff] checkCollection: -> # console.log "#{@faction}: Checking validity of squad against collection..." if @collection? [squadPossible, missingStuff] = @isSquadPossibleWithCollection() @collection_invalid_container.toggleClass 'd-none', squadPossible @collection_invalid_container.on 'mouseover', (e) => @showTooltip 'MissingStuff', missingStuff toXWS: -> # Often you will want JSON.stringify(builder.toXWS()) xws = description: @getNotes() faction: exportObj.toXWSFaction[@faction] name: @current_squad.name pilots: [] points: @total_points vendor: yasb: builder: 'YASB 2.0' builder_url: window.location.href.split('?')[0] link: @getPermaLink() version: '2.0.0' for ship in @ships if ship.pilot? xws.pilots.push ship.toXWS() # Associate multisection ships # This maps id to list of pilots it comprises multisection_id_to_pilots = {} last_id = 0 unmatched = (pilot for pilot in xws.pilots when pilot.multisection?) for _ in [0...(unmatched.length ** 2)] break if unmatched.length == 0 # console.log "Top of loop, unmatched: #{m.name for m in unmatched}" unmatched_pilot = unmatched.shift() unmatched_pilot.multisection_id ?= last_id++ multisection_id_to_pilots[unmatched_pilot.multisection_id] ?= [unmatched_pilot] break if unmatched.length == 0 # console.log "Finding matches for #{unmatched_pilot.name} (assigned id=#{unmatched_pilot.multisection_id})" matches = [] for candidate in unmatched # console.log "-> examine #{candidate.name}" if unmatched_pilot.name in candidate.multisection matches.push candidate unmatched_pilot.multisection.removeItem candidate.name candidate.multisection.removeItem unmatched_pilot.name candidate.multisection_id = unmatched_pilot.multisection_id # console.log "-> MATCH FOUND #{candidate.name}, assigned id=#{candidate.multisection_id}" multisection_id_to_pilots[candidate.multisection_id].push candidate if unmatched_pilot.multisection.length == 0 # console.log "-> No more sections to match for #{unmatched_pilot.name}" break for match in matches if match.multisection.length == 0 # console.log "Dequeue #{match.name} since it has no more sections to match" unmatched.removeItem match for pilot in xws.pilots delete pilot.multisection if pilot.multisection? obstacles = @getObstacles() if obstacles? and obstacles.length > 0 xws.obstacles = obstacles xws toMinimalXWS: -> # Just what's necessary xws = @toXWS() # Keep mandatory stuff only for own k, v of xws delete xws[k] unless k in ['faction', 'pilots', 'version'] for own k, v of xws.pilots delete xws[k] unless k in ['id', 'upgrades', 'multisection_id'] xws loadFromXWS: (xws, cb) -> success = null error = null if xws.version? version_list = (parseInt x for x in xws.version.split('.')) else version_list = [0,2] # Version tag is optional, so let's just assume it is some 2.0 xws if no version is given switch # Not doing backward compatibility pre-1.x when version_list > [0, 1] xws_faction = exportObj.fromXWSFaction[xws.faction] if @faction != xws_faction throw new Error("Attempted to load XWS for #{xws.faction} but builder is #{@faction}") if xws.name? @current_squad.name = xws.name if xws.description? @notes.val xws.description if xws.obstacles? @current_squad.additional_data.obstacles = xws.obstacles @suppress_automatic_new_ship = true @removeAllShips() success = true error = "" serialized_squad = "v8ZsZ200Z" # serialization version 7, standard squad, 200 points # serialization schema SHIPID:UPGRADEID,UPGRADEID,...,UPGRADEID:;SHIPID:UPGRADEID,... for pilot in xws.pilots new_ship = @addShip() # we add some backward compatibility here, to allow imports from Launch Bay Next Squad Builder # According to xws-spec, for 2nd edition we use id instead of name # however, we will accept a name instead of an id as well. if pilot.id pilotxws = pilot.id else if pilot.name pilotxws = pilot.name else success = false error = "Pilot without identifier" break # add pilot id if exportObj.pilotsByFactionXWS[xws_faction][pilotxws]? serialized_squad += exportObj.pilotsByFactionXWS[xws_faction][pilotxws][0].id else if exportObj.pilotsByUniqueName[pilotxws] and exportObj.pilotsByUniqueName[pilotxws].length == 1 serialized_squad += exportObj.pilotsByUniqueName[pilotxws][0].id else for key, possible_pilots of exportObj.pilotsByUniqueName for possible_pilot in possible_pilots if (possible_pilot.xws and possible_pilot.xws == pilotxws) or (not possible_pilot.xws and key == pilotxws) serialized_squad += possible_pilot.id break serialized_squad += "X" # add upgrade ids # Turn all the upgrades into a flat list so we can keep trying to add them addons = [] for upgrade_type, upgrade_canonicals of pilot.upgrades ? {} for upgrade_canonical in upgrade_canonicals # console.log upgrade_type, upgrade_canonical slot = null slot = exportObj.fromXWSUpgrade[upgrade_type] ? upgrade_type.capitalize() upgrade = exportObj.upgradesBySlotXWSName[slot][upgrade_canonical] ?= exportObj.upgradesBySlotCanonicalName[slot][upgrade_canonical] if not upgrade? console.log("Failed to load xws upgrade: " + upgrade_canonical) error += "Skipped upgrade " + upgrade_canonical success = false continue serialized_squad += upgrade.id serialized_squad += "W" serialized_squad += "XY" @loadFromSerialized(serialized_squad) @current_squad.dirty = true @container.trigger 'xwing-backend:squadNameChanged' @container.trigger 'xwing-backend:squadDirtinessChanged' cb success: success error: error class Ship constructor: (args) -> # args @builder = args.builder @container = args.container # internal state @pilot = null @data = null # ship data @quickbuildId = -1 @linkedShip = null # some quickbuilds contain two ships, this variable may reference a Ship beeing part of the same quickbuild card @primary = true # only the primary ship of a linked ship pair will contribute points and serialization id @upgrades = [] @wingmates = [] # stores wingmates (quickbuild stuff only) @destroystate = null @setupUI() destroy: (cb) -> @resetPilot() @resetAddons() @teardownUI() idx = @builder.ships.indexOf this if idx < 0 throw new Error("Ship not registered with builder") @builder.ships.splice idx, 1 if @wingmates.length > 0 @setWingmates(0) else if @linkedShip != null @linkedShip.linkedShip = null if @linkedShip.wingmates?.length > 0 @linkedShip.removeFromWing(this) else await @builder.removeShip @linkedShip, defer() cb() copyFrom: (other) -> throw new Error("Cannot copy from self") if other is this #console.log "Attempt to copy #{other?.pilot?.name}" return unless other.pilot? and other.data? #console.log "Setting pilot to ID=#{other.pilot.id}" if @builder.isQuickbuild if not (other.pilot.unique or (other.pilot.max_per_squad? and @builder.countPilots(other.pilot.canonical_name) >= other.pilot.max_per_squad)) # check if any upgrades are unique. In that case the whole ship may not be copied no_uniques_involved = true for upgrade in other.upgrades if (upgrade.data?.unique? and upgrade.data.unique) or (upgrade.data?.max_per_squad? and @builder.countUpgrades(upgrade.data.canonical_name) >= upgrade.data.max_per_squad) or upgrade.data?.solitary? no_uniques_involved = false # select cheapest generic like above available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled) if available_pilots.length > 0 @setPilotById available_pilots[0].id, true break else return if no_uniques_involved @setPilotById other.quickbuildId else if other.pilot.unique or (other.pilot.max_per_squad? and @builder.countPilots(other.pilot.canonical_name) >= other.pilot.max_per_squad) # Look for cheapest generic or available unique, otherwise do nothing available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled) if available_pilots.length > 0 @setPilotById available_pilots[0].id, true else return else @setPilotById other.pilot.id, true # Can't just copy upgrades since slots may be different other_upgrades = {} for upgrade in other.upgrades if upgrade?.data? and not upgrade.data.unique and ((not upgrade.data.max_per_squad?) or @builder.countUpgrades(upgrade.data.canonical_name) < upgrade.data.max_per_squad) other_upgrades[upgrade.slot] ?= [] other_upgrades[upgrade.slot].push upgrade delayed_upgrades = {} for upgrade in @upgrades other_upgrade = (other_upgrades[upgrade.slot] ? []).shift() if other_upgrade? upgrade.setById other_upgrade.data.id if not upgrades.lastSetValid delayed_upgrades[other_upgrade.data.id] = upgrade for id, upgrade of delayed_upgrades upgrade.setById id @addStandardizedUpgrades() @updateSelections() @builder.container.trigger 'xwing:pointsUpdated' @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' setShipType: (ship_type) -> @pilot_selector.data('select2').container.show() if ship_type != @pilot?.ship if not @builder.isQuickbuild # Ship changed; select first non-unique pilot = (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not exportObj.pilotsById[result.id].unique)[0] if pilot # if there is a non-unique, use this one @setPilot pilot else # otherwise just set it to the first available pilot @setPilot (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when ((not exportObj.pilotsById[result.id].restriction_func? or exportObj.pilotsById[result.id].restriction_func(@)) and not (exportObj.pilotsById[result.id] in @builder.uniques_in_use.Pilot)))[0] else # get the first available pilot quickbuild_id = (result.id for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not result.disabled)[0] @setPilotById quickbuild_id @checkPilotSelectorQueryModal() # Clear ship background class for cls in @row.attr('class').split(/\s+/) if cls.indexOf('ship-') == 0 @row.removeClass cls # Show delete button @remove_button.fadeIn 'fast' @copy_button.fadeIn 'fast' @points_destroyed_button.fadeIn 'fast' # Ship background @row.addClass "ship-#{ship_type.toLowerCase().replace(/[^a-z0-9]/gi, '')}" @builder.container.trigger 'xwing:shipUpdated' setPilotById: (id, noautoequip = false) -> #sets pilot of this ship according to given id. Id might be pilotId or quickbuildId depending on mode. if not @builder.isQuickbuild @setPilot exportObj.pilotsById[parseInt id], noautoequip else if id != @quickbuildId @wingmate_selector.parent().hide() if @wingmates? and @wingmates.length > 0 # remove any wingmates, as the wing leader was just removed from the list @setWingmates(0) @linkedShip = null @quickbuildId = id @builder.current_squad.dirty = true @resetPilot() @resetAddons() if id? and id > -1 quickbuild = exportObj.quickbuildsById[parseInt id] new_pilot = exportObj.pilots[quickbuild.pilot] @data = exportObj.ships[quickbuild.ship] @builder.isUpdatingPoints = true # prevents unneccesary validations while still adding stuff if new_pilot?.unique? await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ] @pilot = new_pilot @setupAddons() if @pilot? @copy_button.show() @setShipType @pilot.ship # if this card contains more than one ship, make sure the other one is added as well if quickbuild.wingmate? && not @linkedShip? # try to join wingleader, if we have not been created by him for ship in @builder.ships if ship.quickbuildId == quickbuild.linkedId # found our leader. join him. ship.joinWing(this) @linkedShip = ship @primary = false @builder.isUpdatingPoints = false @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' return # we are done. if @linkedShip # we are already linked to some other ship if quickbuild.linkedId? # we will stay linked to another ship, so just set the linked one to an new pilot es well @linkedShip.setPilotById quickbuild.linkedId @linkedShip.primary = false unless quickbuild.wingmate? else # take care of associated ship if @linkedShip.wingmates?.length > 0 # we are no longer part of a wing @linkedShip.removeFromWing(this) else # we are no longer part of a linked pair, so the linked ship should be removed @linkedShip.linkedShip = null await @builder.removeShip @linkedShip, defer() @linkedShip = null else if quickbuild.linkedId? # we nare not already linked to another ship, but need one. Let's set one up @linkedShip = @builder.ships.slice(-1)[0] # during squad building there is an empty ship at the bottom, use that one and add a new empty one. # during squad loading there is no empty ship at the bottom, so we just create a new one and use it if @linkedShip.data != null @linkedShip = @builder.addShip() else @builder.addShip() @linkedShip.linkedShip = this @linkedShip.setPilotById quickbuild.linkedId # for pairs the first selected ship is master, so as we have been created first, we set the other ship to false # for wings the wingleader is always master, so we don't set the other ship to false, if we are just a wingmate @linkedShip.primary = false unless quickbuild.wingmate? @primary = !quickbuild.wingmate? if quickbuild?.wingleader? @wingmate_selector.parent().show() @wingmate_selector.val quickbuild.wingmates[0] @wingmate_selector.attr "min", quickbuild.wingmates[0] @wingmate_selector.attr "max", quickbuild.wingmates[quickbuild.wingmates.length - 1] @setWingmates quickbuild.wingmates[0] @builder.isUpdatingPoints = false @builder.container.trigger 'xwing:pointsUpdated' else @copy_button.hide() @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' addStandardizedUpgrades: -> idx = @builder.standard_list['Ship'].indexOf @data.name if idx > -1 for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, @builder.standard_list['Upgrade'][idx].slot) upgrade.setData @builder.standard_list['Upgrade'][idx] break setPilot: (new_pilot, noautoequip = false) -> # don't call this method directly, unless you know what you do. Use setPilotById for proper quickbuild handling if new_pilot != @pilot @builder.current_squad.dirty = true same_ship = @pilot? and new_pilot?.ship == @pilot.ship old_upgrades = {} if same_ship # track addons and try to reassign them for upgrade in @upgrades if upgrade?.data? old_upgrades[upgrade.slot] ?= [] old_upgrades[upgrade.slot].push upgrade @resetPilot() @resetAddons() if new_pilot? @data = exportObj.ships[new_pilot?.ship] if new_pilot?.unique? await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ] @pilot = new_pilot @setupAddons() if @pilot? @copy_button.show() @setShipType @pilot.ship @addStandardizedUpgrades() if (@pilot.autoequip? or (exportObj.ships[@pilot.ship].autoequip? and not same_ship)) and not noautoequip autoequip = (@pilot.autoequip ? []).concat(exportObj.ships[@pilot.ship].autoequip ? []) for upgrade_name in autoequip auto_equip_upgrade = exportObj.upgrades[upgrade_name] for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, auto_equip_upgrade.slot) upgrade.setData auto_equip_upgrade if same_ship delayed_upgrades = {} for upgrade in @upgrades old_upgrade = (old_upgrades[upgrade.slot] ? []).shift() if old_upgrade? upgrade.setById old_upgrade.data.id if not upgrade.lastSetValid delayed_upgrades[old_upgrade.data.id] = upgrade for id, upgrade of delayed_upgrades upgrade.setById id else @copy_button.hide() @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' resetPilot: -> if @pilot?.unique? await @builder.container.trigger 'xwing:releaseUnique', [ @pilot, 'Pilot', defer() ] @pilot = null setupAddons: -> if not @builder.isQuickbuild # Upgrades from pilot for slot in @pilot.slots ? [] @upgrades.push new exportObj.Upgrade ship: this container: @addon_container slot: slot else # Upgrades from quickbuild for upgrade_name in exportObj.quickbuildsById[@quickbuildId].upgrades ? [] upgrade_data = exportObj.upgrades[upgrade_name] if not upgrade_data? console.log("Unknown Upgrade: " + upgrade_name) continue upgrade = new exportObj.QuickbuildUpgrade ship: this container: @addon_container slot: upgrade_data.slot upgrade: upgrade_data upgrade.setData upgrade_data @upgrades.push upgrade resetAddons: -> await for upgrade in @upgrades upgrade.destroy defer() if upgrade? @upgrades = [] getPoints: -> if not @builder.isQuickbuild points = @pilot?.points ? 0 for upgrade in @upgrades points += upgrade.getPoints() @points_container.find('span').text points if points > 0 @points_container.fadeTo 'fast', 1 else @points_container.fadeTo 0, 0 points else quickbuild = exportObj.quickbuildsById[@quickbuildId] threat = if @primary then quickbuild?.threat ? 0 else 0 if quickbuild?.wingleader? threat = quickbuild.threat[quickbuild.wingmates.indexOf(@wingmates.length)] @points_container.find('span').text threat if threat > 0 @points_container.fadeTo 'fast', 1 else @points_container.fadeTo 0, 0 threat setWingmates: (wingmates) -> # creates/destroys wingmates to match number given as argument # todo: Check if number is valid for this quickbuild wing? if @wingmates?.length == wingmates # nothing to do, we already have correct number of wingmates. return if !@wingmates? || @wingmates.length == 0 # if no wingmates are set yet, use the linked buddy @wingmates = [@linkedShip] quickbuild = exportObj.quickbuildsById[@quickbuildId] while @wingmates.length < wingmates # create more wingmates newMate = @builder.ships.slice(-1)[0] # during squad building there is an empty ship at the bottom, use that one and add a new empty one. # during squad loading there is no empty ship at the bottom, so we just create a new one and use it if newMate.data != null newMate = @builder.addShip() else @builder.addShip() newMate.linkedShip = this # link new mate to us @wingmates.push(newMate) newMate.setPilotById quickbuild.linkedId # for pairs the first selected ship is master, so as we have been created first, we set the other ship to false # for wings the wingleader is always master, so we don't set the other ship to false, if we are just a wingmate newMate.primary = false @primary = true # he should not try to steal our primary position, as he is aware of beeing not squad leader, but in case he's not just set it. while @wingmates.length > wingmates # destroy wingmates dyingMate = @wingmates.pop() dyingMate.linkedShip = null # prevent the mate from killing us await @builder.removeShip dyingMate, defer() @wingmate_selector.val wingmates removeFromWing: (ship) -> # remove requested ship from wing @wingmates.removeItem(ship) # check if the wing is still valid, otherwise destroy it. quickbuild = exportObj.quickbuildsById[@quickbuildId] if !(@wingmates.length in quickbuild.wingmates) @destroy $.noop @wingmate_selector.val @wingmates.length joinWing: (ship) -> # remove requested ship from wing @wingmates.push(ship) # check if the wing is still valid, otherwise destroy the added ship quickbuild = exportObj.quickbuildsById[@quickbuildId] if !(@wingmates.length in quickbuild.wingmates) ship.destroy $.noop @removeFromWing(ship) @wingmate_selector.val @wingmates.length updateSelections: -> if @pilot? @ship_selector.select2 'data', id: @pilot.ship text: if exportObj.ships[@pilot.ship].display_name then exportObj.ships[@pilot.ship].display_name else @pilot.ship xws: exportObj.ships[@pilot.ship].xws icon: if exportObj.ships[@pilot.ship].icon then exportObj.ships[@pilot.ship].icon else exportObj.ships[@pilot.ship].xws @pilot_selector.select2 'data', id: @pilot.id text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then @pilot.skill + ' - ' else ''}#{if @pilot.display_name then @pilot.display_name else @pilot.name}#{if @quickbuildId != -1 then exportObj.quickbuildsById[@quickbuildId].suffix else ""} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})" @pilot_selector.data('select2').container.show() for upgrade in @upgrades points = upgrade.getPoints() upgrade.updateSelection points else @pilot_selector.select2 'data', null #@pilot_selector.data('select2').container.toggle(@ship_selector.val() != '') checkPilotSelectorQueryModal: -> if $(window).width() >= 768 @pilot_query_modal.hide() else if @pilot then @pilot_query_modal.show() setupUI: -> @row = $ document.createElement 'DIV' @row.addClass 'row ship mb-5 mb-sm-0' @row.insertBefore @builder.notes_container if @pilot? shipicon = if exportObj.ships[@pilot.ship].icon then exportObj.ships[@pilot.ship].icon else exportObj.ships[@pilot.ship].xws @row.append $.trim ''' <div class="col-md-3"> <div class="form-group d-flex"> <input class="ship-selector-container" type="hidden"></input> <div class="input-group-append"> <button class="btn btn-secondary d-block d-md-none ship-query-modal"><i class="fas fa-question"></i></button> </div> <br /> </div> <div class="form-group d-flex"> <input type="hidden" class="pilot-selector-container"></input> <div class="input-group-append"> <button class="btn btn-secondary pilot-query-modal"><i class="fas fa-question"></i></button> <br /> </div> </div> <label class="wingmate-label"> Wingmates: <input type="number" class="wingmate-selector"></input> </label> </div> <div class="col-md-1 points-display-container"> <span></span> </div> <div class="col-md-6 addon-container"> </div> <div class="col-md-2 button-container"> <button class="btn btn-danger remove-pilot side-button"><span class="d-none d-sm-block" data-toggle="tooltip" title="Remove Pilot"><i class="fa fa-times"></i></span><span class="d-block d-sm-none"> Remove Pilot</span></button> <button class="btn btn-light copy-pilot side-button"><span class="d-none d-sm-block" data-toggle="tooltip" title="Clone Pilot"><i class="far fa-copy"></i></span><span class="d-block d-sm-none"> Clone Pilot</span></button>&nbsp;&nbsp;&nbsp; <button class="btn btn-light points-destroyed side-button" points-state"><span class="destroyed-type" title="Points Destroyed"><i class="xwing-miniatures-font xwing-miniatures-font-title"></i></span></button> </div> ''' @row.find('.button-container span').tooltip() @ship_selector = $ @row.find('input.ship-selector-container') @pilot_selector = $ @row.find('input.pilot-selector-container') @wingmate_selector = $ @row.find('input.wingmate-selector') @ship_query_modal = $ @row.find('button.ship-query-modal') @pilot_query_modal = $ @row.find('button.pilot-query-modal') @ship_query_modal.click (e) => if @pilot @builder.showTooltip 'Ship', exportObj.ships[@pilot.ship], null, @builder.mobile_tooltip_modal, true @builder.mobile_tooltip_modal.modal 'show' @pilot_query_modal.click (e) => if @pilot @builder.showTooltip 'Pilot', @pilot, (@ if @pilot), @builder.mobile_tooltip_modal, true @builder.mobile_tooltip_modal.modal 'show' shipResultFormatter = (object, container, query) -> return """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.icon}"></i> #{object.text}""" shipSelectionFormatter = (object, container) -> return """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.icon}"></i> #{object.text}""" @ship_selector.select2 width: '100%' placeholder: exportObj.translate @builder.language, 'ui', 'shipSelectorPlaceholder' query: (query) => data = {results: []} data.results = @builder.getAvailableShipsMatching(query.term) query.callback(data) minimumResultsForSearch: if $.isMobile() then -1 else 0 formatResultCssClass: (obj) => if @builder.collection? and (@builder.collection.checks.collectioncheck == "true") not_in_collection = false if @pilot? and obj.id == exportObj.ships[@pilot.ship].id # Currently selected ship; mark as not in collection if it's neither # on the shelf nor on the table unless (@builder.collection.checkShelf('ship', obj.name) or @builder.collection.checkTable('pilot', obj.name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @builder.collection.checkShelf('ship', obj.name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' formatResult: shipResultFormatter formatSelection: shipResultFormatter @ship_selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @ship_selector.on 'change', (e) => @setShipType @ship_selector.val() @ship_selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' @builder.showTooltip 'Ship', exportObj.ships[select2_data.id] if select2_data?.id? @ship_selector.data('select2').container.on 'mouseover', (e) => @builder.showTooltip 'Ship', exportObj.ships[@pilot.ship] if @pilot @pilot_selector.select2 width: '100%' placeholder: exportObj.translate @builder.language, 'ui', 'pilotSelectorPlaceholder' query: (query) => data = {results: []} data.results = @builder.getAvailablePilotsForShipIncluding(@ship_selector.val(), (if not @builder.isQuickbuild then @pilot else @quickbuildId), query.term, true, @) query.callback(data) minimumResultsForSearch: if $.isMobile() then -1 else 0 formatResultCssClass: (obj) => if @builder.collection? and (@builder.collection.checks.collectioncheck == "true") not_in_collection = false name = "" if @builder.isQuickbuild name = exportObj.quickbuildsById[obj.id]?.pilot ? "unknown pilot" else name = obj.name if obj.id == @pilot?.id # Currently selected pilot; mark as not in collection if it's neither # on the shelf nor on the table unless (@builder.collection.checkShelf('pilot', name) or @builder.collection.checkTable('pilot', name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @builder.collection.checkShelf('pilot', name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' @pilot_selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @pilot_selector.on 'change', (e) => @setPilotById @pilot_selector.select2('val') @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' @builder.backend_status.fadeOut 'slow' @pilot_selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' if @builder.isQuickbuild @builder.showTooltip 'Quickbuild', exportObj.quickbuildsById[select2_data.id], {ship: @data?.name} if select2_data?.id? else @builder.showTooltip 'Pilot', exportObj.pilotsById[select2_data.id] if select2_data?.id? @pilot_selector.data('select2').container.on 'mouseover', (e) => @builder.showTooltip 'Pilot', @pilot, @ if @pilot @pilot_selector.data('select2').container.hide() if @builder.isQuickbuild @wingmate_selector.on 'change', (e) => @setWingmates parseInt @wingmate_selector.val() @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' @builder.backend_status.fadeOut 'slow' @wingmate_selector.on 'mousemove-filtered', (e) => return # TODO: show tooltip of wingmate # select2_data = $(e.target).closest('.select2-result').data 'select2-data' # if @builder.isQuickbuild # @builder.showTooltip 'Quickbuild', exportObj.quickbuildsById[select2_data.id], {ship: @data?.name} if select2_data?.id? # else # @builder.showTooltip 'Pilot', exportObj.wingmatesById[select2_data.id] if select2_data?.id? # @wingmate_selector.on 'mouseover', (e) => # @builder.showTooltip 'Pilot', @wingmate, @ if @wingmate # @wingmate_selector.parent().hide() @points_container = $ @row.find('.points-display-container') @points_container.fadeTo 0, 0 @addon_container = $ @row.find('div.addon-container') @remove_button = $ @row.find('button.remove-pilot') @remove_button.click (e) => e.preventDefault() @row.slideUp 'fast', () => @builder.removeShip this @backend_status?.fadeOut 'slow' @remove_button.hide() @copy_button = $ @row.find('button.copy-pilot') @copy_button.click (e) => clone = @builder.ships[@builder.ships.length - 1] clone.copyFrom(this) @copy_button.hide() @checkPilotSelectorQueryModal() @points_destroyed_button_span = $ @row.find('.destroyed-type') @points_destroyed_button = $ @row.find('button.points-destroyed') @points_destroyed_button.click (e) => if @destroystate == 1 @destroystate = 2 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-crit"></i>' else if @destroystate == 2 @destroystate = 0 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-title"></i>' else @destroystate = 1 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-hit"></i>' @builder.onPointsUpdated() @points_destroyed_button.hide() teardownUI: -> @row.text '' @row.remove() toString: -> if @pilot? "Pilot #{if @pilot.display_name then @pilot.display_name else @pilot.name} flying #{if @data.display_name then @data.display_name else @data.name}" else "Ship without pilot" toHTML: -> effective_stats = @effectiveStats() action_bar = @builder.formatActions(effective_stats.actions,"&nbsp;&nbsp;", @pilot.keyword ? []) attack_icon = @data.attack_icon ? 'xwing-miniatures-font-frontarc' engagementHTML = if (@pilot.engagement?) then $.trim """ <span class="info-data info-skill">ENG #{@pilot.engagement}</span> """ else '' attackHTML = if (effective_stats.attack?) then $.trim """ <i class="xwing-miniatures-font header-attack #{attack_icon}"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attack ? @data.attack), effective_stats, 'attack')}</span> """ else '' if effective_stats.attackbull? attackbullHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackbull ? @data.attackbull), effective_stats, 'attackbull')}</span>""" else attackbullHTML = '' if effective_stats.attackb? attackbHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackb ? @data.attackb), effective_stats, 'attackb')}</span>""" else attackbHTML = '' if effective_stats.attackf? attackfHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackf ? @data.attackf), effective_stats, 'attackf')}</span>""" else attackfHTML = '' if effective_stats.attackt? attacktHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackt ? @data.attackt), effective_stats, 'attackt')}</span>""" else attacktHTML = '' if effective_stats.attackl? attacklHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-leftarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackl ? @data.attackl), effective_stats, 'attackl')}</span>""" else attacklHTML = '' if effective_stats.attackr? attackrHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-rightarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackr ? @data.attackr), effective_stats, 'attackr')}</span>""" else attackrHTML = '' if effective_stats.attackdt? attackdtHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackdt ? @data.attackdt), effective_stats, 'attackdt')}</span>""" else attackdtHTML = '' recurringicon = '' if @data.energyrecurr? count = 0 while count < @data.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count energyHTML = if (@pilot.ship_override?.energy? or @data.energy?) then $.trim """ <i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i> <span class="info-data info-energy">#{statAndEffectiveStat((@pilot.ship_override?.energy ? @data.energy), effective_stats, 'energy')}#{recurringicon}</span> """ else '' forceHTML = if (@pilot.force?) then $.trim """ <i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i> <span class="info-data info-force">#{statAndEffectiveStat((@pilot.ship_override?.force ? @pilot.force), effective_stats, 'force')}<sup><i class="fas fa-caret-up"></i></sup></span> """ else '' if @pilot.charge? recurringicon = '' if @pilot.recurring? if @pilot.recurring > 0 count = 0 while count < @pilot.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = @pilot.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """<i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i><span class="info-data info-charge">#{statAndEffectiveStat((@pilot.ship_override?.charge ? @pilot.charge), effective_stats, 'charge')}#{recurringicon}</span>""" else chargeHTML = '' shieldRECUR = '' if @data.shieldrecurr? count = 0 while count < @data.shieldrecurr shieldRECUR += """<sup><i class="fas fa-caret-up"></i></sup>""" ++count shieldIconHTML = '' if effective_stats.shields for _ in [effective_stats.shields..2] by -1 shieldIconHTML += """<i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield expanded-hull-or-shield"></i>""" shieldIconHTML += """<i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i>""" hullIconHTML = '' if effective_stats.hull for _ in [effective_stats.hull..2] by -1 hullIconHTML += """<i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull expanded-hull-or-shield"></i>""" hullIconHTML += """<i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i>""" html = $.trim """ <div class="fancy-pilot-header"> <div class="pilot-header-text">#{if @pilot.display_name then @pilot.display_name else @pilot.name} <i class="xwing-miniatures-ship xwing-miniatures-ship-#{@data.xws}"></i><span class="fancy-ship-type"> #{if @data.display_name then @data.display_name else @data.name}</span></div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle pilot-points">#{if @quickbuildId != -1 then (if @primary then @getPoints() else '*') else @pilot.points}</div> </div> </div> </div> <div class="fancy-pilot-stats"> <div class="pilot-stats-content"> <span class="info-data info-skill">INI #{statAndEffectiveStat(@pilot.skill, effective_stats, 'skill')}</span> #{engagementHTML} #{attackbullHTML} #{attackHTML} #{attackbHTML} #{attackfHTML} #{attacktHTML} #{attacklHTML} #{attackrHTML} #{attackdtHTML} <i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i> <span class="info-data info-agility">#{statAndEffectiveStat((@pilot.ship_override?.agility ? @data.agility), effective_stats, 'agility')}</span> #{hullIconHTML} <span class="info-data info-hull">#{statAndEffectiveStat((@pilot.ship_override?.hull ? @data.hull), effective_stats, 'hull')}</span> #{shieldIconHTML} <span class="info-data info-shields">#{statAndEffectiveStat((@pilot.ship_override?.shields ? @data.shields), effective_stats, 'shields')}#{shieldRECUR}</span> #{energyHTML} #{forceHTML} #{chargeHTML} <br /> #{action_bar} </div> </div> """ # Maneuver Dials have been moved at the bottom of the squad, rather than beeing added to each ship # dialHTML = @builder.getManeuverTableHTML(effective_stats.maneuvers, @data.maneuvers) # # html += $.trim """ # <div class="fancy-dial"> # #{dialHTML} # </div> # """ if @pilot.text html += $.trim """ <div class="fancy-pilot-text">#{@pilot.text}</div> """ slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 html += $.trim """ <div class="fancy-upgrade-container"> """ for upgrade in slotted_upgrades points = upgrade.getPoints() html += upgrade.toHTML points html += $.trim """ </div> """ HalfPoints = Math.ceil @getPoints() / 2 Threshold = Math.ceil (effective_stats['hull'] + effective_stats['shields']) / 2 html += $.trim """ <div class="ship-points-total"> <strong>Ship Total: #{@getPoints()}, Half Points: #{HalfPoints}, Threshold: #{Threshold}</strong> </div> """ """<div class="fancy-ship">#{html}</div>""" toTableRow: -> table_html = $.trim """ <tr class="simple-pilot"> <td class="name">#{if @pilot.display_name then @pilot.display_name else @pilot.name} &mdash; #{if @data.display_name then @data.display_name else @data.name}</td> <td class="points">#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points}</td> </tr> """ slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades points = upgrade.getPoints() table_html += upgrade.toTableRow points # if @getPoints() != @pilot.points table_html += """<tr class="simple-ship-total"><td colspan="2">Ship Total: #{@getPoints()}</td></tr>""" halfPoints = Math.ceil @getPoints() / 2 threshold = Math.ceil (@effectiveStats()['hull'] + @effectiveStats()['shields']) / 2 table_html += """<tr class="simple-ship-half-points"><td colspan="2">Half Points: #{halfPoints} Threshold: #{threshold}</td></tr>""" table_html += '<tr><td>&nbsp;</td><td></td></tr>' table_html toSimpleCopy: -> simplecopy = """#{@pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points}) \n""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 simplecopy +=" " simplecopy_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_simplecopy = upgrade.toSimpleCopy points simplecopy_upgrades.push upgrade_simplecopy if upgrade_simplecopy? simplecopy += simplecopy_upgrades.join " " simplecopy += """ \n""" halfPoints = Math.ceil @getPoints() / 2 threshold = Math.ceil (@effectiveStats()['hull'] + @effectiveStats()['shields']) / 2 simplecopy += """Ship total: #{@getPoints()} Half Points: #{halfPoints} Threshold: #{threshold} \n \n""" simplecopy toRedditText: -> reddit = """**#{@pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})** \n""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 reddit +=" " reddit_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_reddit = upgrade.toRedditText points reddit_upgrades.push upgrade_reddit if upgrade_reddit? reddit += reddit_upgrades.join " " reddit += """&nbsp;*Ship total: (#{@getPoints()})* \n""" reddit toTTSText: -> tts = """#{exportObj.toTTS(@pilot.name)}""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades upgrade_tts = upgrade.toTTSText() tts += (" + " + upgrade_tts) if upgrade_tts? tts += " / " toBBCode: -> bbcode = """[b]#{if @pilot.display_name then @pilot.display_name else @pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})[/b]""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 bbcode +="\n" bbcode_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_bbcode = upgrade.toBBCode points bbcode_upgrades.push upgrade_bbcode if upgrade_bbcode? bbcode += bbcode_upgrades.join "\n" bbcode toSimpleHTML: -> html = """<b>#{if @pilot.display_name then @pilot.display_name else @pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})</b><br />""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_html = upgrade.toSimpleHTML points html += upgrade_html if upgrade_html? html toSerialized: -> # PILOT_ID:UPGRADEID1,UPGRADEID2:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2 if @builder.isQuickbuild if (!@wingmates? || @wingmates.length == 0) then """#{@quickbuildId}X""" else """#{@quickbuildId}X#{@wingmates.length}""" else upgrades = """#{upgrade?.data?.id ? "" for upgrade, i in @upgrades}""".replace(/,/g, "W") [ @pilot.id, upgrades, ].join 'X' fromSerialized: (version, serialized) -> # adds a ship from the given serialized data to the squad. # returns true, if all upgrades have been added successfully, false otherwise # returning false does not necessary mean nothing has been added, but some stuff might have been dropped (e.g. 0-0-0 if vader is not yet in the squad) everythingadded = true switch version # version 1-3 are 1st edition x-wing only, so we may as well delete them. # version 4 was the final version of 1st edition, and the first few weeks of 2nd edition. # version 5 is the current version. It handles titles and mods as regular upgrades. when 4, 5, 6 # PILOT_ID:UPGRADEID1,UPGRADEID2:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2 # conferredaddons are upgrade slots added by e.g. titles # version 5 is the same as version 4, but title and mod has been dropped (as they are treated as upgrades anyways). Thus, we may differ by length if (serialized.split ':').length == 3 # version 5,6 [ pilot_id, upgrade_ids, conferredaddon_pairs ] = serialized.split ':' else # version 4 [ pilot_id, upgrade_ids, version_4_compatibility_placeholder_title, version_4_compatibility_placeholder_mod, conferredaddon_pairs ] = serialized.split ':' @setPilotById parseInt(pilot_id), true # make sure the pilot is valid return false unless @validate deferred_ids = [] for upgrade_id, i in upgrade_ids.split ',' upgrade_id = parseInt upgrade_id continue if upgrade_id < 0 or isNaN(upgrade_id) # Defer fat upgrades if @upgrades[i].isOccupied() or @upgrades[i].dataById[upgrade_id]?.also_occupies_upgrades? deferred_ids.push upgrade_id else @upgrades[i].setById upgrade_id everythingadded &= @upgrades[i].lastSetValid for deferred_id in deferred_ids deferred_id_added = false for upgrade, i in @upgrades if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot continue upgrade.setById deferred_id deferred_id_added = upgrade.lastSetValid break everythingadded &= deferred_id_added if conferredaddon_pairs? conferredaddon_pairs = conferredaddon_pairs.split ',' else conferredaddon_pairs = [] for upgrade in @upgrades if upgrade?.data? and upgrade.conferredAddons.length > 0 upgrade_conferred_addon_pairs = conferredaddon_pairs.splice 0, upgrade.conferredAddons.length for conferredaddon_pair, i in upgrade_conferred_addon_pairs [ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.' addon_id = parseInt addon_id addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized] if not addon_cls console.log("Something went wrong... could not serialize properly") continue conferred_addon = upgrade.conferredAddons[i] if conferred_addon instanceof addon_cls conferred_addon.setById addon_id everythingadded &= conferred_addon.lastSetValid else throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there") when 7, 8 pilot_splitter = if version > 7 then 'X' else ':' upgrade_splitter = if version > 7 then 'W' else ',' # version 7 is an further extension of version 6, allowing arbitrary order of upgrades. It currently ignores conferredaddons (upgrades in slots added by titles etc), probably we can drop the special case handling for them and include them into the usual upgrade list? [ pilot_id, upgrade_ids, conferredaddon_pairs ] = serialized.split pilot_splitter upgrade_ids = upgrade_ids.split upgrade_splitter # set the pilot @setPilotById parseInt(pilot_id), true # make sure the pilot is valid return false unless @validate if !@builder.isQuickbuild # iterate over upgrades to be added, and remove all that have been successfully added for _ in [1 ... 3] # try adding each upgrade a few times, as the required slots might be added in by titles etc and are not yet available on the first try for i in [upgrade_ids.length - 1 ... -1] upgrade_id = upgrade_ids[i] upgrade = exportObj.upgradesById[upgrade_id] if not upgrade? upgrade_ids.splice(i,1) # Remove unknown or empty ID if upgrade_id != "" console.log("Unknown upgrade id " + upgrade_id + " could not be added. Please report that error") everythingadded = false continue for upgrade_selection in @upgrades if exportObj.slotsMatching(upgrade.slot, upgrade_selection.slot) and not upgrade_selection.isOccupied() upgrade_selection.setById upgrade_id if upgrade_selection.lastSetValid upgrade_ids.splice(i,1) # added successfully, remove from list break else # we are in quickbuild. Number of wingmates might be provided as upgrade ID of a quickbuild if upgrade_ids.length > 0 && @wingmates.length > 0 # check if we are actually a wingleader @setWingmates(upgrade_ids[0]) everythingadded &= upgrade_ids.length == 0 @updateSelections() everythingadded effectiveStats: -> stats = attack: @pilot.ship_override?.attack ? @data.attack attackf: @pilot.ship_override?.attackf ? @data.attackf attackbull: @pilot.ship_override?.attackbull ? @data.attackbull attackb: @pilot.ship_override?.attackb ? @data.attackb attackt: @pilot.ship_override?.attackt ? @data.attackt attackl: @pilot.ship_override?.attackl ? @data.attackl attackr: @pilot.ship_override?.attackr ? @data.attackr attackdt: @pilot.ship_override?.attackdt ? @data.attackdt energy: @pilot.ship_override?.energy ? @data.energy agility: @pilot.ship_override?.agility ? @data.agility hull: @pilot.ship_override?.hull ? @data.hull shields: @pilot.ship_override?.shields ? @data.shields force: (@pilot.ship_override?.force ? @pilot.force) ? 0 charge: @pilot.ship_override?.charge ? @pilot.charge actions: (@pilot.ship_override?.actions ? @data.actions).slice 0 # need a deep copy of maneuvers array stats.maneuvers = [] for s in [0 ... (@data.maneuvers ? []).length] stats.maneuvers[s] = @data.maneuvers[s].slice 0 # Droid conversion of Focus to Calculate if @pilot.keyword? and ("Droid" in @pilot.keyword) and stats.actions? new_stats = [] for statentry in stats.actions new_stats.push statentry.replace("Focus","Calculate") stats.actions = new_stats for upgrade in @upgrades upgrade.data.modifier_func(stats) if upgrade?.data?.modifier_func? @pilot.modifier_func(stats) if @pilot?.modifier_func? stats validate: -> # Remove addons that violate their validation functions (if any) one by one # until everything checks out # If there is no explicit validation_func, use restriction_func # Returns true, if nothing has been changed, and false otherwise # check if we are an empty selection, which is always valid if not @pilot? return true unchanged = true max_checks = 32 # that's a lot of addons if @builder.isEpic #Command Epic adding if not ("Command" in @pilot.slots) addCommand = true for upgrade in @upgrades if ("Command" == upgrade.slot) and (this == upgrade.ship) addCommand = false if addCommand == true @upgrades.push new exportObj.Upgrade ship: this container: @addon_container slot: "Command" else if !@builder.isQuickbuild #cleanup Command upgrades for i in [@upgrades.length - 1 ... -1] upgrade = @upgrades[i] if upgrade.slot == "Command" upgrade.destroy $.noop @upgrades.splice i,1 for i in [0...max_checks] valid = true pilot_func = @pilot?.validation_func ? @pilot?.restriction_func ? undefined if (pilot_func? and not pilot_func(this, @pilot)) or not (@builder.isItemAvailable(@pilot, true)) # we go ahead and happily remove ourself. Of course, when calling a method like validate on an object, you have to expect that it will dissappear, right? @builder.removeShip this return false # no need to check anything further, as we do not exist anymore # everything is limited in X-Wing 2.0, so we need to check if any upgrade is equipped more than once equipped_upgrades = [] for upgrade in @upgrades func = upgrade?.data?.validation_func ? undefined if func? func_result = upgrade?.data?.validation_func(this, upgrade) else if upgrade?.data?.restrictions func_result = @restriction_check(upgrade.data.restrictions, upgrade) # check if either a) validation func not met or b) upgrade already equipped (in 2.0 everything is limited) or c) upgrade is not available (e.g. not Hyperspace legal) # ignore those checks if this is a quickbuild squad, as quickbuild does whatever it wants to do... if ((func_result? and not func_result) or (upgrade?.data? and (upgrade.data in equipped_upgrades or (upgrade.data.faction? and not @builder.isOurFaction(upgrade.data.faction,@pilot.faction)) or not @builder.isItemAvailable(upgrade.data)))) and not @builder.isQuickbuild #console.log "Invalid upgrade: #{upgrade?.data?.name}" upgrade.setById null valid = false unchanged = false break if upgrade?.data? and upgrade.data equipped_upgrades.push(upgrade?.data) break if valid @updateSelections() unchanged checkUnreleasedContent: -> if @pilot? and not exportObj.isReleased @pilot #console.log "#{@pilot.name} is unreleased" return true for upgrade in @upgrades if upgrade?.data? and not exportObj.isReleased upgrade.data #console.log "#{upgrade.data.id} is unreleased" return true false hasAnotherUnoccupiedSlotLike: (upgrade_obj, upgradeslot) -> for upgrade in @upgrades continue if upgrade == upgrade_obj or upgrade.slot != upgradeslot return true unless upgrade.isOccupied() false restriction_check: (restrictions, upgrade_obj) -> effective_stats = @effectiveStats() for r in restrictions if r[0] == "orUnique" if @checkListForUnique(r[1].toLowerCase().replace(/[^0-9a-z]/gi, '').replace(/\s+/g, '-')) return true switch r[0] when "Base" switch r[1] when "Small" if @data.medium? or @data.large? or @data.huge? then return false when "Small or Medium" if @data.large? or @data.huge? then return false when "Medium" if not (@data.medium?) then return false when "Medium or Large" if not (@data.medium? or @data.large?) then return false when "Large" if not (@data.large?) then return false when "Huge" if not (@data.huge?) then return false when "Standard" if @data.huge? then return false when "Action" if not ((r[1] in effective_stats.actions) or ("*#{r[1]}" in effective_stats.actions) or ("F-#{r[1]}" in effective_stats.actions) or ("R-#{r[1]}" in effective_stats.actions)) then return false when "Keyword" if not (@checkKeyword(r[1])) then return false when "Equipped" if not ((@doesSlotExist(r[1]) and not @hasAnotherUnoccupiedSlotLike(upgrade_obj, r[1]))) then return false when "Slot" if not @hasAnotherUnoccupiedSlotLike(upgrade_obj, r[1]) then return false when "AttackArc" if not @data.attackb? then return false when "ShieldsGreaterThan" if not (@data.shields > r[1]) then return false when "EnergyGreatterThan" if not (effective_stats.energy > r[1]) then return false when "InitiativeGreaterThan" if not (@pilot.skill > r[1]) then return false when "InitiativeLessThan" if not (@pilot.skill < r[1]) then return false when "AgilityEquals" if not (effective_stats.agility == r[1]) then return false when "isUnique" if r[1] != @pilot.unique? then return false when "Format" switch r[1] when "Epic" if not (@data.name in exportObj.epicExclusionsList) then return false when "Standard" if @data.name in exportObj.epicExclusionsList then return false when "Faction" if @pilot.faction != r[1] then return false return true doesSlotExist: (slot) -> for upgrade in @upgrades if slot == upgrade.slot return true false isSlotOccupied: (slot_name) -> for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, slot_name) return true unless upgrade.isOccupied() false checkKeyword: (keyword) -> if @data.name?.includes(keyword) return true for words in @data.keyword ? [] if words == keyword return true for words in @pilot.keyword ? [] if words == keyword return true for upgrade in @upgrades for word in upgrade?.data?.keyword ? [] if word == keyword return true false checkListForUnique: (name) -> for t, things of @builder.uniques_in_use if t != 'Slot' return true if name in (thing.canonical_name.getXWSBaseName() for thing in things) false toXWS: -> xws = id: (@pilot.xws ? @pilot.canonical_name) name: (@pilot.xws ? @pilot.canonical_name) # name is no longer part of xws 2.0.0, and was replaced by id. However, we will add it here for some kind of backward compatibility. May be removed, as soon as everybody is using id. points: @getPoints() #ship: @data.canonical_name ship: @data.xws.canonicalize() if @data.multisection xws.multisection = @data.multisection.slice 0 upgrade_obj = {} for upgrade in @upgrades if upgrade?.data? upgrade.toXWS upgrade_obj if Object.keys(upgrade_obj).length > 0 xws.upgrades = upgrade_obj xws getConditions: -> if Set? conditions = new Set() if @pilot?.applies_condition? if @pilot.applies_condition instanceof Array for condition in @pilot.applies_condition conditions.add(exportObj.conditionsByCanonicalName[condition]) else conditions.add(exportObj.conditionsByCanonicalName[@pilot.applies_condition]) for upgrade in @upgrades if upgrade?.data?.applies_condition? if upgrade.data.applies_condition instanceof Array for condition in upgrade.data.applies_condition conditions.add(exportObj.conditionsByCanonicalName[condition]) else conditions.add(exportObj.conditionsByCanonicalName[upgrade.data.applies_condition]) conditions else console.warn 'Set not supported in this JS implementation, not implementing conditions' [] class GenericAddon constructor: (args) -> # args @ship = args.ship @container = $ args.container # internal state @data = null @unadjusted_data = null @conferredAddons = [] @serialization_code = 'X' @occupied_by = null @occupying = [] @destroyed = false # Overridden by children @type = null @dataByName = null @dataById = null @adjustment_func = args.adjustment_func if args.adjustment_func? @filter_func = args.filter_func if args.filter_func? @placeholderMod_func = if args.placeholderMod_func? then args.placeholderMod_func else (x) => x destroy: (cb, args...) -> return cb(args) if @destroyed if @data?.unique? await @ship.builder.container.trigger 'xwing:releaseUnique', [ @data, @type, defer() ] if @data?.standardized? @removeStandardized() @destroyed = true @rescindAddons() @deoccupyOtherUpgrades() @selector.select2 'destroy' @selectorwrap.remove() cb args setupSelector: (args) -> @selectorwrap = $ document.createElement 'div' @selectorwrap.addClass 'form-group d-flex upgrade-box' @selector = $ document.createElement 'INPUT' @selector.attr 'type', 'hidden' @selectorwrap.append @selector @selectorwrap.append $.trim ''' <div class="input-group-addon"> <button class="btn btn-secondary d-block d-md-none upgrade-query-modal"><i class="fas fa-question"></i></button> </div> ''' @upgrade_query_modal = $ @selectorwrap.find('button.upgrade-query-modal') @container.append @selectorwrap args.minimumResultsForSearch = -1 if $.isMobile() args.formatResultCssClass = (obj) => if @ship.builder.collection? not_in_collection = false if obj.id == @data?.id # Currently selected card; mark as not in collection if it's neither # on the shelf nor on the table unless (@ship.builder.collection.checkShelf(@type.toLowerCase(), obj.name) or @ship.builder.collection.checkTable(@type.toLowerCase(), obj.name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @ship.builder.collection.checkShelf(@type.toLowerCase(), obj.name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' args.formatSelection = (obj, container) => icon = switch @type when 'Upgrade' @slot.toLowerCase().replace(/[^0-9a-z]/gi, '') else @type.toLowerCase().replace(/[^0-9a-z]/gi, '') icon = icon.replace("configuration", "config") .replace("force", "forcepower") # Append directly so we don't have to disable markup escaping $(container).append """<i class="xwing-miniatures-font xwing-miniatures-font-#{icon}"></i> #{obj.text}""" # If you return a string, Select2 will render it undefined @selector.select2 args @upgrade_query_modal.click (e) => if @data console.log "#{@data.name}" @ship.builder.showTooltip 'Addon', @data, ({addon_type: @type} if @data?) , @ship.builder.mobile_tooltip_modal, true @ship.builder.mobile_tooltip_modal.modal 'show' @selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @selector.on 'change', (e) => @setById @selector.select2('val') @ship.builder.current_squad.dirty = true @ship.builder.container.trigger 'xwing-backend:squadDirtinessChanged' @ship.builder.backend_status.fadeOut 'slow' @selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' @ship.builder.showTooltip 'Addon', @dataById[select2_data.id], {addon_type: @type} if select2_data?.id? @selector.data('select2').container.on 'mouseover', (e) => @ship.builder.showTooltip 'Addon', @data, {addon_type: @type} if @data? setById: (id) -> @setData @dataById[parseInt id] setByName: (name) -> @setData @dataByName[$.trim name] setData: (new_data) -> if new_data?.id != @data?.id if @data?.unique? or @data?.solitary? await @ship.builder.container.trigger 'xwing:releaseUnique', [ @unadjusted_data, @type, defer() ] if @data?.standardized? @removeStandardized() @rescindAddons() @deoccupyOtherUpgrades() if new_data?.unique? or new_data?.solitary? try await @ship.builder.container.trigger 'xwing:claimUnique', [ new_data, @type, defer() ] catch alreadyClaimed @ship.builder.container.trigger 'xwing:pointsUpdated' @lastSetValid = false return # Need to make a copy of the data, but that means I can't just check equality @data = @unadjusted_data = new_data if @data? if @data.superseded_by_id return @setById @data.superseded_by_id if @adjustment_func? @data = @adjustment_func(@data) @unequipOtherUpgrades() @occupyOtherUpgrades() @conferAddons() if @data.standardized? @addToStandardizedList() else @deoccupyOtherUpgrades() # this will remove not allowed upgrades (is also done on pointsUpdated). We do it explicitly so we can tell if the setData was successfull @lastSetValid = @ship.validate() @ship.builder.container.trigger 'xwing:pointsUpdated' addToStandardizedList: -> # check first if standard combo exists and return if it does idx = @ship.builder.standard_list['Ship'].indexOf @ship.data.name if idx > -1 if @ship.builder.standard_list['Upgrade'][idx]?.name == @data.name return @ship.builder.standard_list['Upgrade'].push @data @ship.builder.standard_list['Ship'].push @ship.data.name removeStandardized: -> # removes the ship upgrade combo from the stanard list array idx = @ship.builder.standard_list['Ship'].indexOf @ship.data.name if idx > -1 if @ship.builder.standard_list['Upgrade'][idx]?.name == @data.name @ship.builder.standard_list['Upgrade'].splice idx,1 @ship.builder.standard_list['Ship'].splice idx,1 # now remove all upgrades of the same name nameToRemove = @data.name for ship in @ship.builder.ships if ship.data?.name == @ship.data.name for upgrade in ship.upgrades if upgrade.data?.name == nameToRemove upgrade.data = null conferAddons: -> if @data.confersAddons? and !@ship.builder.isQuickbuild and @data.confersAddons.length > 0 for addon in @data.confersAddons cls = addon.type args = ship: @ship container: @container args.slot = addon.slot if addon.slot? args.adjustment_func = addon.adjustment_func if addon.adjustment_func? args.filter_func = addon.filter_func if addon.filter_func? args.auto_equip = addon.auto_equip if addon.auto_equip? args.placeholderMod_func = addon.placeholderMod_func if addon.placeholderMod_func? addon = new cls args if addon instanceof exportObj.Upgrade @ship.upgrades.push addon else throw new Error("Unexpected addon type for addon #{addon}") @conferredAddons.push addon rescindAddons: -> await for addon in @conferredAddons addon.destroy defer() for addon in @conferredAddons if addon instanceof exportObj.Upgrade @ship.upgrades.removeItem addon else throw new Error("Unexpected addon type for addon #{addon}") @conferredAddons = [] getPoints: (data = @data, ship = @ship) -> # Moar special case jankiness if data?.variableagility? data?.pointsarray[ship.data.agility] else if data?.variablebase? if ship?.data.medium? data?.pointsarray[1] else if ship?.data.large? data?.pointsarray[2] else if ship?.data.huge? data?.pointsarray[3] else data?.pointsarray[0] else if data?.variableinit? data?.pointsarray[ship.pilot.skill] else data?.points ? 0 updateSelection: (points) -> if @data? @selector.select2 'data', id: @data.id text: "#{if @data.display_name then @data.display_name else @data.name} (#{points}#{if @data.pointsarray then '*' else ''})" else @selector.select2 'data', null toString: -> if @data? "#{if @data.display_name then @data.display_name else @data.name} (#{@getPoints()})" else "No #{@type}" toHTML: (points) -> if @data? if @data.slot? and @data.slot == "HardpointShip" upgrade_slot_font = "hardpoint" else upgrade_slot_font = (@data.slot ? @type).toLowerCase().replace(/[^0-9a-z]/gi, '') match_array = @data.text?match(/(<span.*<\/span>)<br \/><br \/>(.*)/) if match_array restriction_html = '<div class="card-restriction-container">' + match_array[1] + '</div>' text_str = match_array[2] else restriction_html = '' text_str = @data.text attackHTML = "" if @data.range? attackrangebonus = if (@data.rangebonus?) then """<span class="upgrade-attack-rangebonus"><i class="xwing-miniatures-font xwing-miniatures-font-rangebonusindicator"></i></span>""" else '' attackStats = $.trim """ <span class="upgrade-attack-range">#{@data.range}</span> #{attackrangebonus} """ attackIcon = if (@data.attack?) then $.trim """ <span class="info-data info-attack">#{@data.attack}</span> <i class="xwing-miniatures-font xwing-miniatures-font-frontarc"></i> """ else if (@data.attackt?) then $.trim """ <span class="info-data info-attack">#{@data.attackt}</span> <i class="xwing-miniatures-font xwing-miniatures-font-singleturretarc"></i> """ else if (@data.attackdt?) then $.trim """ <span class="info-data info-attack">#{@data.attackdt}</span> <i class="xwing-miniatures-font xwing-miniatures-font-doubleturretarc"></i> """ else if (@data.attackl?) then $.trim """ <span class="info-data info-attack">#{@data.attackl}</span> <i class="xwing-miniatures-font xwing-miniatures-font-leftarc"></i> """ else if (@data.attackr?) then $.trim """ <span class="info-data info-attack">#{@data.attackr}</span> <i class="xwing-miniatures-font xwing-miniatures-font-rightarc"></i> """ else if (@data.attackbull?) then $.trim """ <span class="info-data info-attack">#{@data.attackbull}</span> <i class="xwing-miniatures-font xwing-miniatures-font-bullseyearc"></i> """ else '' attackHTML = $.trim """ <div class="upgrade-attack"> #{attackStats} #{attackIcon} </div> """ if @data.charge? recurringicon = '' if @data.recurring? if @data.recurring > 0 count = 0 while count < @data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = @data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """ <div class="upgrade-charge"> <span class="info-data info-charge">#{@data.charge}</span> <i class="xwing-miniatures-font xwing-miniatures-font-charge"></i>#{recurringicon} </div> """ else chargeHTML = $.trim '' if (@data.force?) forceHTML = $.trim """ <div class="upgrade-force"> <span class="info-data info-force">#{@data.force}</span> <i class="xwing-miniatures-font xwing-miniatures-font-forcecharge"></i><sup><i class="fas fa-caret-up"></i></sup> </div> """ else forceHTML = $.trim '' $.trim """ <div class="upgrade-container"> <div class="upgrade-stats"> <div class="upgrade-name"><i class="xwing-miniatures-font xwing-miniatures-font-#{upgrade_slot_font}"></i>#{if @data.display_name then @data.display_name else @data.name}</div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle upgrade-points">#{points}</div> </div> </div> #{restriction_html} </div> #{attackHTML} #{chargeHTML} #{forceHTML} <div class="upgrade-text">#{text_str}</div> <div style="clear: both;"></div> </div> """ else '' toTableRow: (points) -> if @data? $.trim """ <tr class="simple-addon"> <td class="name">#{if @data.display_name then @data.display_name else @data.name}</td> <td class="points">#{points}</td> </tr> """ else '' toSimpleCopy: (points) -> if @data? """#{@data.name} (#{points}) \n""" else null toRedditText: (points) -> if @data? """*&nbsp;#{@data.name} (#{points})* \n""" else null toTTSText: () -> if @data? """#{exportObj.toTTS(@data.name)}""" else null toBBCode: (points) -> if @data? """[i]#{if @data.display_name then @data.display_name else @data.name} (#{points})[/i]""" else null toSimpleHTML: (points) -> if @data? """<i>#{if @data.display_name then @data.display_name else @data.name} (#{points})</i><br />""" else '' toSerialized: -> """#{@serialization_code}.#{@data?.id ? -1}""" unequipOtherUpgrades: -> for slot in @data?.unequips_upgrades ? [] for upgrade in @ship.upgrades continue if upgrade.slot != slot or upgrade == this or not upgrade.isOccupied() upgrade.setData null break isOccupied: -> @data? or @occupied_by? occupyOtherUpgrades: -> for slot in @data?.also_occupies_upgrades ? [] for upgrade in @ship.upgrades continue if upgrade.slot != slot or upgrade == this or upgrade.isOccupied() @occupy upgrade break deoccupyOtherUpgrades: -> for upgrade in @occupying @deoccupy upgrade occupy: (upgrade) -> upgrade.occupied_by = this upgrade.selector.select2 'enable', false @occupying.push upgrade deoccupy: (upgrade) -> upgrade.occupied_by = null upgrade.selector.select2 'enable', true occupiesAnUpgradeSlot: (upgradeslot) -> for upgrade in @ship.upgrades continue if upgrade.slot != upgradeslot or upgrade == this or upgrade.data? if upgrade.occupied_by? and upgrade.occupied_by == this return true false toXWS: (upgrade_dict) -> (upgrade_dict[exportObj.toXWSUpgrade[@data.slot] ? @data.slot.canonicalize()] ?= []).push (@data.xws ? @data.canonical_name) class exportObj.Upgrade extends GenericAddon constructor: (args) -> # args super args @slot = args.slot @type = 'Upgrade' @dataById = exportObj.upgradesById @dataByName = exportObj.upgrades @serialization_code = 'U' @setupSelector() setupSelector: -> super width: '100%' placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'upgradePlaceholder', @slot) allowClear: true query: (query) => data = {results: []} data.results = @ship.builder.getAvailableUpgradesIncluding(@slot, @data, @ship, this, query.term, @filter_func) query.callback(data) class exportObj.RestrictedUpgrade extends exportObj.Upgrade constructor: (args) -> @filter_func = args.filter_func super args @serialization_code = 'u' if args.auto_equip? @setById args.auto_equip class exportObj.QuickbuildUpgrade extends GenericAddon constructor: (args) -> super args @slot = args.slot @type = 'Upgrade' @dataById = exportObj.upgradesById @dataByName = exportObj.upgrades @serialization_code = 'U' @upgrade = args.upgrade @setupSelector() setupSelector: -> super width: '100%' allowClear: false query: (query) => data = { results: [{ id: @upgrade.id text: if @upgrade.display_name then @upgrade.display_name else @upgrade.name points: 0 name: @upgrade.name display_name: @upgrade.display_name }] } query.callback(data) getPoints: (args) -> 0 updateSelection: (args) -> if @data? @selector.select2 'data', id: @data.id text: "#{if @data.display_name then @data.display_name else @data.name}" else @selector.select2 'data', null SERIALIZATION_CODE_TO_CLASS = 'U': exportObj.Upgrade 'u': exportObj.RestrictedUpgrade
true
### X-Wing Squad Builder 2.0 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> https://raithos.github.io ### exportObj = exports ? this exportObj.sortHelper = (a, b) -> if a.points == b.points a_name = a.text.replace(/[^a-z0-9]/ig, '') b_name = b.text.replace(/[^a-z0-9]/ig, '') if a_name == b_name 0 else if a_name > b_name then 1 else -1 else if typeof(a.points) == "string" # handling cases where points value is "*" instead of a number 1 else if a.points > b.points then 1 else -1 exportObj.toTTS = (txt) -> if not txt? null else txt.replace(/\(.*\)/g,"").replace("�",'"').replace("�",'"') exportObj.slotsMatching = (slota, slotb) -> return true if slota == slotb return false if slota != 'HardpointShip' and slotb != 'HardpointShip' return true if slota == 'Torpedo' or slota == 'Cannon' or slota == 'Missile' return true if slotb == 'Torpedo' or slotb == 'Cannon' or slotb == 'Missile' return false $.isMobile = -> if (navigator.userAgent.match /(iPhone|iPod|iPad|Android)/i) or navigator.maxTouchPoints > 1 return true return false $.randomInt = (n) -> Math.floor(Math.random() * n) $.isElementInView = (element, fullyInView) -> pageTop = $(window).scrollTop() pageBottom = pageTop + $(window).height() elementTop = $(element).offset().top elementBottom = elementTop + $(element).height() if fullyInView return ((pageTop < elementTop) && (pageBottom > elementBottom)) else return ((elementTop <= pageBottom) && (elementBottom >= pageTop)) # ripped from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values $.getParameterByName = (name) -> name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") regexS = "[\\?&]" + name + "=([^&#]*)" regex = new RegExp(regexS) results = regex.exec(window.location.search) if results == null return "" else return decodeURIComponent(results[1].replace(/\+/g, " ")) Array::intersects = (other) -> for item in this if item in other return true return false Array::removeItem = (item) -> idx = @indexOf item @splice(idx, 1) unless idx == -1 this String::capitalize = -> @charAt(0).toUpperCase() + @slice(1) String::getXWSBaseName = -> @split('-')[0] URL_BASE = "#{window.location.protocol}//#{window.location.host}#{window.location.pathname}" SQUAD_DISPLAY_NAME_MAX_LENGTH = 24 statAndEffectiveStat = (base_stat, effective_stats, key) -> if base_stat? """#{base_stat}#{if (effective_stats? and effective_stats[key]? and effective_stats[key] != base_stat) then " (#{effective_stats[key]})" else ""}""" else if effective_stats? and effective_stats[key]? """0 (#{effective_stats[key]})""" else "0" getPrimaryFaction = (faction) -> switch faction when 'Rebel Alliance' 'Rebel Alliance' when 'Galactic Empire' 'Galactic Empire' else faction conditionToHTML = (condition) -> html = $.trim """ <div class="condition"> <div class="name">#{if condition.unique then "&middot;&nbsp;" else ""}#{if condition.display_name then condition.display_name else condition.name}</div> <div class="text">#{condition.text}</div> </div> """ # Assumes cards.js will be loaded class exportObj.SquadBuilder constructor: (args) -> # args @container = $ args.container @faction = $.trim args.faction @printable_container = $ args.printable_container @tab = $ args.tab # internal state @ships = [] @uniques_in_use = Pilot: [] Upgrade: [] Slot: [] @standard_list = Upgrade: [] Ship: [] @suppress_automatic_new_ship = false @tooltip_currently_displaying = null @randomizer_options = sources: null points: 200 bid_goal: 5 ships_or_upgrades: 3 ship_limit: 0 collection_only: true fill_zero_pts: false @total_points = 0 # a squad given in the link is loaded on construction of that builder. It will set all gamemodes of already existing builders accordingly, but we did not exists back than. So we copy over the gamemode @isHyperspace = exportObj.builders[0]?.isHyperspace ? false @isEpic = exportObj.builders[0]?.isEpic ? false @isQuickbuild = exportObj.builders[0]?.isQuickbuild ? false @backend = null @current_squad = {} @language = 'English' @collection = null @current_obstacles = [] @setupUI() @game_type_selector.val (exportObj.builders[0] ? @).game_type_selector.val() @setupEventHandlers() window.setInterval @updatePermaLink, 250 @isUpdatingPoints = false if $.getParameterByName('f') == @faction @resetCurrentSquad(true) @loadFromSerialized $.getParameterByName('d') else @resetCurrentSquad() @addShip() resetCurrentSquad: (initial_load=false) -> default_squad_name = 'Unnamed Squadron' squad_name = $.trim(@squad_name_input.val()) or default_squad_name if initial_load and $.trim $.getParameterByName('sn') squad_name = $.trim $.getParameterByName('sn') squad_obstacles = [] if initial_load and $.trim $.getParameterByName('obs') squad_obstacles = ($.trim $.getParameterByName('obs')).split(",").slice(0, 3) @current_obstacles = squad_obstacles else if @current_obstacles squad_obstacles = @current_obstacles @current_squad = id: null name: squad_name dirty: false additional_data: points: @total_points description: '' cards: [] notes: '' obstacles: squad_obstacles tag: '' faction: @faction if @total_points > 0 if squad_name == default_squad_name @current_squad.name = 'Unsaved Squadron' @current_squad.dirty = true @container.trigger 'xwing-backend:squadNameChanged' @container.trigger 'xwing-backend:squadDirtinessChanged' newSquadFromScratch: (squad_name = 'PI:NAME:<NAME>END_PI Squadron') -> @squad_name_input.val squad_name @removeAllShips() @addShip() if not @suppress_automatic_new_ship @current_obstacles = [] @resetCurrentSquad() @notes.val '' @tag.val '' setupUI: -> DEFAULT_RANDOMIZER_POINTS = 200 DEFAULT_RANDOMIZER_TIMEOUT_SEC = 4 DEFAULT_RANDOMIZER_BID_GOAL = 5 DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES = 3 DEFAULT_RANDOMIZER_SHIP_LIMIT = 0 @status_container = $ document.createElement 'DIV' @status_container.addClass 'container-fluid' @status_container.append $.trim ''' <div class="row squad-name-and-points-row"> <div class="col-md-3 squad-name-container"> <div class="display-name"> <span class="squad-name"></span> <i class="far fa-edit"></i> </div> <div class="input-append"> <input type="text" maxlength="64" placeholder="Name your squad..." /> <button class="btn save"><i class="fa fa-pen-square"></i></button> </div> <br /> <select class="game-type-selector"> <option value="standard">Extended</option> <option value="hyperspace">Hyperspace</option> <option value="epic">Epic</option> <option value="quickbuild">Quickbuild</option> </select> </div> <div class="col-md-4 points-display-container"> Points: <span class="total-points">0</span> / <input type="number" class="desired-points" value="200"> <span class="points-remaining-container">(<span class="points-remaining"></span>&nbsp;left) <span class="points-destroyed red"></span></span> <span class="content-warning unreleased-content-used d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning loading-failed-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning collection-invalid d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated"></span></span> <span class="content-warning ship-number-invalid-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated">A tournament legal squad must contain 2-8 ships!</span></span> <span class="content-warning multi-faction-warning-container d-none"><br /><i class="fa fa-exclamation-circle"></i>&nbsp;<span class="translated">Multi-Faction Lists are NEVER tournament legal!</span></span> </div> <div class="col-md-5 float-right button-container"> <div class="btn-group float-right"> <button class="btn btn-info view-as-text"><span class="d-none d-lg-block"><i class="fa fa-print"></i>&nbsp;Print/Export</span><span class="d-lg-none"><i class="fa fa-print"></i></span></button> <a class="btn btn-primary d-none collection"><span class="d-none d-lg-block"><i class="fa fa-folder-open"></i> Your Collection</span><span class="d-lg-none"><i class="fa fa-folder-open"></i></span></a> <!-- Randomize button is marked as danger, since it creates a new squad --> <button class="btn btn-danger randomize"><span class="d-none d-lg-block"><i class="fa fa-random"></i> Randomize!</span><span class="d-lg-none"><i class="fa fa-random"></i></span></button> <button class="btn btn-danger dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a class="dropdown-item randomize-options">Randomizer Options</a></li> <li><a class="dropdown-item misc-settings">Misc Settings</a></li> </ul> </div> </div> </div> <div class="row squad-save-buttons"> <div class="col-md-12"> <button class="show-authenticated btn btn-primary save-list"><i class="far fa-save"></i>&nbsp;Save</button> <button class="show-authenticated btn btn-primary save-list-as"><i class="far fa-file"></i>&nbsp;Save As...</button> <button class="show-authenticated btn btn-primary delete-list disabled"><i class="fa fa-trash"></i>&nbsp;Delete</button> <button class="show-authenticated btn btn-info backend-list-my-squads show-authenticated"><i class="fa fa-download"></i>&nbsp;Load Squad</button> <button class="btn btn-info import-squad"><i class="fa fa-file-import"></i>&nbsp;Import</button> <button class="btn btn-danger clear-squad"><i class="fa fa-plus-circle"></i>&nbsp;New Squad</button> <span class="show-authenticated backend-status"></span> </div> </div> ''' @container.append @status_container @xws_import_modal = $ document.createElement 'DIV' @xws_import_modal.addClass 'modal fade import-modal d-print-none' @xws_import_modal.tabindex = "-1" @xws_import_modal.role = "dialog" @xws_import_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>XWS Import</h3> <button type="button" class="close d-print-none" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> Import your list via XWS into YASB.<br> <i>XWS is a common format to share lists between applications.</i> <div class="container-fluid"> <textarea class="xws-content" placeholder="Paste XWS here"></textarea> </div> </div> <div class="modal-footer d-print-none"> <span class="xws-import-status"></span>&nbsp; <button class="btn btn-danger import-xws">Import</button> </div> </div> </div> """ @from_xws_button = @container.find('button.import-squad') @from_xws_button.click (e) => e.preventDefault() @xws_import_modal.find('.xws-import-status').text ' ' @xws_import_modal.modal 'show' @load_xws_button = $ @xws_import_modal.find('button.import-xws') @load_xws_button.click (e) => e.preventDefault() exportObj.loadXWSButton(@xws_import_modal) @container.append @xws_import_modal @list_modal = $ document.createElement 'DIV' @list_modal.addClass 'modal fade text-list-modal' @list_modal.tabindex = "-1" @list_modal.role = "dialog" @container.append @list_modal @list_modal.append $.trim """ <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <div class="d-print-none"> <h4 class="modal-title"><span class="squad-name"></span> (<span class="total-points"></span>)</h4> </div> <div class="d-none d-print-block"> <div class="fancy-header"> <div class="squad-name"></div> <div class="squad-faction"></div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle"> <span class="total-points"></span> </div> </div> </div> </div> <div class="fancy-under-header"></div> </div> <button type="button" class="close d-print-none" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <div class="fancy-list"></div> <div class="simple-list"></div> <div class="simplecopy-list"> <p>Copy the below and paste it elsewhere.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="reddit-list"> <p>Copy the below and paste it into your reddit post.</p> <p>Make sure that the post editor is set to markdown mode.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="tts-list"> <p>Copy the below and paste it into the Tabletop Simulator.</p> <textarea></textarea><br /><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="bbcode-list"> <p>Copy the BBCode below and paste it into your forum post.</p> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="html-list"> <textarea></textarea><button class="btn btn-modal btn-copy">Copy</button> </div> <div class="xws-list"> <p>Copy and paste this into an XWS-compliant application. <div class="row full-row"> <div class="col d-inline-block d-none d-sm-block"><textarea></textarea><br /><button class="btn btn-modal btn-copy">Copy</button></div> <div class="col d-inline-block d-none d-sm-block qrcode-container" id="xws-qrcode-container"></div> </div> </div> </div> <div class="container-fluid modal-footer d-print-none"> <div class="row full-row"> <div class="col d-inline-block d-none d-sm-block right-col"> <label class="color-skip-text-checkbox"> Skip Card Text <input type="checkbox" class="toggle-skip-text-print" /> </label><br /> <label class="vertical-space-checkbox"> Add Space for Cards <input type="checkbox" class="toggle-vertical-space" /> </label><br /> <label class="maneuver-print-checkbox"> Include Maneuvers Chart <input type="checkbox" class="toggle-maneuver-print" /> </label><br /> <label class="expanded-shield-hull-print-checkbox"> Expand Shield and Hull <input type="checkbox" class="toggle-expanded-shield-hull-print" /> </label> </div> <div class="col d-inline-block d-none d-sm-block right-col"> <label class="color-print-checkbox"> Print Color <input type="checkbox" class="toggle-color-print" checked="checked" /> </label><br /> <label class="qrcode-checkbox"> Include QR codes <input type="checkbox" class="toggle-juggler-qrcode" checked="checked" /> </label><br /> <label class="obstacles-checkbox"> Include Obstacle Choices <input type="checkbox" class="toggle-obstacles" /> </label> </div> </div> <div class="row btn-group list-display-mode"> <button class="btn btn-modal select-simple-view">Simple</button> <button class="btn btn-modal select-fancy-view d-none d-sm-block">Fancy</button> <button class="btn btn-modal select-simplecopy-view">Text</button> <button class="btn btn-modal select-tts-view">TTS</button> <button class="btn btn-modal select-reddit-view">Reddit</button> <button class="btn btn-modal select-bbcode-view">BBCode</button> <button class="btn btn-modal select-html-view">HTML</button> <button class="btn btn-modal select-xws-view">XWS</button> </div> <button class="btn btn-modal print-list d-none d-sm-block"><i class="fa fa-print"></i>&nbsp;Print</button> </div> </div> </div> """ @fancy_container = $ @list_modal.find('.fancy-list') @fancy_total_points_container = $ @list_modal.find('div.modal-header .total-points') @simple_container = $ @list_modal.find('div.modal-body .simple-list') @reddit_container = $ @list_modal.find('div.modal-body .reddit-list') @reddit_textarea = $ @reddit_container.find('textarea') @reddit_textarea.attr 'readonly', 'readonly' @simplecopy_container = $ @list_modal.find('div.modal-body .simplecopy-list') @simplecopy_textarea = $ @simplecopy_container.find('textarea') @simplecopy_textarea.attr 'readonly', 'readonly' @tts_container = $ @list_modal.find('div.modal-body .tts-list') @tts_textarea = $ @tts_container.find('textarea') @tts_textarea.attr 'readonly', 'readonly' @xws_container = $ @list_modal.find('div.modal-body .xws-list') @xws_textarea = $ @xws_container.find('textarea') @xws_textarea.attr 'readonly', 'readonly' @bbcode_container = $ @list_modal.find('div.modal-body .bbcode-list') @bbcode_textarea = $ @bbcode_container.find('textarea') @bbcode_textarea.attr 'readonly', 'readonly' @htmlview_container = $ @list_modal.find('div.modal-body .html-list') @html_textarea = $ @htmlview_container.find('textarea') @html_textarea.attr 'readonly', 'readonly' @toggle_vertical_space_container = $ @list_modal.find('.vertical-space-checkbox') @toggle_color_print_container = $ @list_modal.find('.color-print-checkbox') @toggle_color_skip_text = $ @list_modal.find('.color-skip-text-checkbox') @toggle_maneuver_dial_container = $ @list_modal.find('.maneuver-print-checkbox') @toggle_expanded_shield_hull_container = $ @list_modal.find('.expanded-shield-hull-print-checkbox') @toggle_qrcode_container = $ @list_modal.find('.qrcode-checkbox') @toggle_obstacle_container = $ @list_modal.find('.obstacles-checkbox') @btn_print_list = ($ @list_modal.find('.print-list'))[0] @list_modal.on 'click', 'button.btn-copy', (e) => @self = $(e.currentTarget) @self.siblings('textarea').select() @success = document.execCommand('copy') if @success @self.addClass 'btn-success' setTimeout ( => @self.removeClass 'btn-success' ), 1000 @select_simple_view_button = $ @list_modal.find('.select-simple-view') @select_simple_view_button.click (e) => @select_simple_view_button.blur() unless @list_display_mode == 'simple' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_simple_view_button.addClass 'btn-inverse' @list_display_mode = 'simple' @simple_container.show() @fancy_container.hide() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @xws_container.hide() @bbcode_container.hide() @htmlview_container.hide() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.show() @toggle_obstacle_container.show() @btn_print_list.disabled = false; @select_fancy_view_button = $ @list_modal.find('.select-fancy-view') @select_fancy_view_button.click (e) => @select_fancy_view_button.blur() unless @list_display_mode == 'fancy' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_fancy_view_button.addClass 'btn-inverse' @list_display_mode = 'fancy' @fancy_container.show() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @bbcode_container.hide() @htmlview_container.hide() @xws_container.hide() @toggle_vertical_space_container.show() @toggle_color_print_container.show() @toggle_color_skip_text.show() @toggle_maneuver_dial_container.show() @toggle_expanded_shield_hull_container.show() @toggle_qrcode_container.show() @toggle_obstacle_container.show() @btn_print_list.disabled = false; @select_reddit_view_button = $ @list_modal.find('.select-reddit-view') @select_reddit_view_button.click (e) => @select_reddit_view_button.blur() unless @list_display_mode == 'reddit' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_reddit_view_button.addClass 'btn-inverse' @list_display_mode = 'reddit' @reddit_container.show() @simplecopy_container.hide() @bbcode_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @reddit_textarea.select() @reddit_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_simplecopy_view_button = $ @list_modal.find('.select-simplecopy-view') @select_simplecopy_view_button.click (e) => @select_simplecopy_view_button.blur() unless @list_display_mode == 'simplecopy' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_simplecopy_view_button.addClass 'btn-inverse' @list_display_mode = 'simplecopy' @reddit_container.hide() @simplecopy_container.show() @bbcode_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @simplecopy_textarea.select() @simplecopy_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_tts_view_button = $ @list_modal.find('.select-tts-view') @select_tts_view_button.click (e) => @select_tts_view_button.blur() unless @list_display_mode == 'tts' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_tts_view_button.addClass 'btn-inverse' @list_display_mode = 'tts' @tts_container.show() @bbcode_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @fancy_container.hide() @tts_textarea.select() @tts_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_bbcode_view_button = $ @list_modal.find('.select-bbcode-view') @select_bbcode_view_button.click (e) => @select_bbcode_view_button.blur() unless @list_display_mode == 'bbcode' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_bbcode_view_button.addClass 'btn-inverse' @list_display_mode = 'bbcode' @bbcode_container.show() @simplecopy_container.hide() @reddit_container.hide() @tts_container.hide() @htmlview_container.hide() @xws_container.hide() @simple_container.hide() @fancy_container.hide() @bbcode_textarea.select() @bbcode_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_html_view_button = $ @list_modal.find('.select-html-view') @select_html_view_button.click (e) => @select_html_view_button.blur() unless @list_display_mode == 'html' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_html_view_button.addClass 'btn-inverse' @list_display_mode = 'html' @reddit_container.hide() @simplecopy_container.hide() @tts_container.hide() @bbcode_container.hide() @htmlview_container.show() @simple_container.hide() @fancy_container.hide() @xws_container.hide() @html_textarea.select() @html_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; @select_xws_view_button = $ @list_modal.find('.select-xws-view') @select_xws_view_button.click (e) => @select_xws_view() if $(window).width() >= 768 @simple_container.hide() @select_fancy_view_button.click() else @select_simple_view_button.click() @clear_squad_button = $ @status_container.find('.clear-squad') @clear_squad_button.click (e) => if @current_squad.dirty and @backend? @backend.warnUnsaved this, () => @newSquadFromScratch() else @newSquadFromScratch() @squad_name_container = $ @status_container.find('div.squad-name-container') @squad_name_display = $ @container.find('.display-name') @squad_name_placeholder = $ @container.find('.squad-name') @squad_name_input = $ @squad_name_container.find('input') @squad_name_save_button = $ @squad_name_container.find('button.save') @squad_name_input.closest('div').hide() @points_container = $ @status_container.find('div.points-display-container') @total_points_span = $ @points_container.find('.total-points') @game_type_selector = $ @status_container.find('.game-type-selector') @game_type_selector.select2 minimumResultsForSearch: -1 @game_type_selector.change (e) => # $(window).trigger 'xwing:gameTypeChanged', @game_type_selector.val() @onGameTypeChanged @game_type_selector.val() @desired_points_input = $ @points_container.find('.desired-points') @desired_points_input.change (e) => @onPointsUpdated $.noop @points_remaining_span = $ @points_container.find('.points-remaining') @points_destroyed_span = $ @points_container.find('.points-destroyed') @points_remaining_container = $ @points_container.find('.points-remaining-container') @unreleased_content_used_container = $ @points_container.find('.unreleased-content-used') @loading_failed_container = $ @points_container.find('.loading-failed-container') @ship_number_invalid_container = $ @points_container.find('.ship-number-invalid-container') @multi_faction_warning_container = $ @points_container.find('.multi-faction-warning-container') @collection_invalid_container = $ @points_container.find('.collection-invalid') @view_list_button = $ @status_container.find('div.button-container button.view-as-text') @randomize_button = $ @status_container.find('div.button-container button.randomize') @customize_randomizer = $ @status_container.find('div.button-container a.randomize-options') @misc_settings = $ @status_container.find('div.button-container a.misc-settings') @backend_status = $ @status_container.find('.backend-status') @backend_status.hide() @collection_button = $ @status_container.find('div.button-container a.collection') @collection_button.click (e) => e.preventDefault() unless @collection_button.prop('disabled') @collection.modal.modal 'show' @squad_name_input.keypress (e) => if e.which == 13 @squad_name_save_button.click() false @squad_name_input.change (e) => @backend_status.fadeOut 'slow' @squad_name_input.blur (e) => @squad_name_input.change() @squad_name_save_button.click() @squad_name_display.click (e) => e.preventDefault() @squad_name_display.hide() @squad_name_input.val $.trim(@current_squad.name) # Because Firefox handles this badly window.setTimeout () => @squad_name_input.focus() @squad_name_input.select() , 100 @squad_name_input.closest('div').show() @squad_name_save_button.click (e) => e.preventDefault() @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' name = @current_squad.name = $.trim(@squad_name_input.val()) if name.length > 0 @squad_name_display.show() @container.trigger 'xwing-backend:squadNameChanged' @squad_name_input.closest('div').hide() @randomizer_options_modal = $ document.createElement('DIV') @randomizer_options_modal.addClass 'modal fade randomizer-modal' @randomizer_options_modal.tabindex = "-1" @randomizer_options_modal.role = "dialog" $('body').append @randomizer_options_modal @randomizer_options_modal.append $.trim """ <div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Random Squad Builder Options</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <form> <label> Maximal desired bid <input type="number" class="randomizer-bid-goal" value="#{DEFAULT_RANDOMIZER_BID_GOAL}" placeholder="#{DEFAULT_RANDOMIZER_BID_GOAL}" /> </label><br /> <label> Maximum Ship Count (0 for no limit) <input type="number" class="randomizer-ship-limit" value="#{DEFAULT_RANDOMIZER_SHIP_LIMIT}" placeholder="#{DEFAULT_RANDOMIZER_SHIP_LIMIT}" /> </label><br /> <label> More upgrades <input type="range" min="0" max="10" class="randomizer-ships-or-upgrades" value="#{DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES}" placeholder="#{DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES}" /> Less upgrades </label><br /> <label> <input type="checkbox" class="randomizer-collection-only" checked="checked"/> Only use items from collection </label><br /> <label> Sets and Expansions (default all) <select class="randomizer-sources" multiple="1" data-placeholder="Use all sets and expansions"> </select> </label><br /> <label> <input type="checkbox" class="randomizer-fill-zero-pts" /> Always fill 0-point slots </label><br /> <label> Maximum Seconds to Spend Randomizing <input type="number" class="randomizer-timeout" value="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" placeholder="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" /> </label> </form> </div> <div class="modal-footer"> <button class="btn btn-primary do-randomize" aria-hidden="true">Randomize!</button> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @randomizer_source_selector = $ @randomizer_options_modal.find('select.randomizer-sources') for expansion in exportObj.expansions opt = $ document.createElement('OPTION') opt.text expansion @randomizer_source_selector.append opt @randomizer_source_selector.select2 width: "100%" minimumResultsForSearch: if $.isMobile() then -1 else 0 @randomizer_collection_selector = ($ @randomizer_options_modal.find('.randomizer-collection-only'))[0] @randomizer_fill_zero_pts = ($ @randomizer_options_modal.find('.randomizer-fill-zero-pts'))[0] @randomize_button.click (e) => e.preventDefault() if @current_squad.dirty and @backend? @backend.warnUnsaved this, () => @randomize_button.click() else points = parseInt @desired_points_input.val() points = DEFAULT_RANDOMIZER_POINTS if (isNaN(points) or points <= 0) bid_goal = parseInt $(@randomizer_options_modal.find('.randomizer-bid-goal')).val() bid_goal = DEFAULT_RANDOMIZER_BID_GOAL if (isNaN(bid_goal) or bid_goal < 0) ship_limit = parseInt $(@randomizer_options_modal.find('.randomizer-ship-limit')).val() ship_limit = DEFAULT_RANDOMIZER_SHIP_LIMIT if (isNaN(ship_limit) or ship_limit < 0) ships_or_upgrades = parseInt $(@randomizer_options_modal.find('.randomizer-ships-or-upgrades')).val() ships_or_upgrades = DEFAULT_RANDOMIZER_SHIPS_OR_UPGRADES if (isNaN(ships_or_upgrades) or ships_or_upgrades < 0) timeout_sec = parseInt $(@randomizer_options_modal.find('.randomizer-timeout')).val() timeout_sec = DEFAULT_RANDOMIZER_TIMEOUT_SEC if (isNaN(timeout_sec) or timeout_sec <= 0) # console.log "points=#{points}, sources=#{@randomizer_source_selector.val()}, timeout=#{timeout_sec}" @randomSquad(points, @randomizer_source_selector.val(), timeout_sec * 1000, bid_goal, ship_limit, ships_or_upgrades, @randomizer_collection_selector.checked, @randomizer_fill_zero_pts.checked) @randomizer_options_modal.find('button.do-randomize').click (e) => e.preventDefault() @randomizer_options_modal.modal('hide') @randomize_button.click() @customize_randomizer.click (e) => e.preventDefault() @randomizer_options_modal.modal() @misc_settings_modal = $ document.createElement('DIV') @misc_settings_modal.addClass 'modal fade' @misc_settings_modal.tabindex = "-1" @misc_settings_modal.role = "dialog" $('body').append @misc_settings_modal @misc_settings_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Miscellaneous Settings</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <label class = "toggle-initiative-prefix-names misc-settings-label"> <input type="checkbox" class="initiative-prefix-names-checkbox misc-settings-checkbox" /> Put INI as prefix in front of names. </label><br /> <label> <input type="checkbox" checked /> Is PI:NAME:<NAME>END_PI the worst? </label> </div> <div class="modal-footer"> <span class="misc-settings-infoline"></span> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @misc_settings_infoline = $ @misc_settings_modal.find('.misc-settings-infoline') @misc_settings_initiative_prefix = $ @misc_settings_modal.find('.initiative-prefix-names-checkbox') if @backend? @backend.getSettings (st) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = st.showInitiativeInFrontOfPilotName? if st.showInitiativeInFrontOfPilotName? @misc_settings_initiative_prefix.prop('checked', true) else @waiting_for_backend ?= [] @waiting_for_backend.push => @backend.getSettings (st) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = st.showInitiativeInFrontOfPilotName? if st.showInitiativeInFrontOfPilotName? @misc_settings_initiative_prefix.prop('checked', true) @misc_settings_initiative_prefix.click (e) => exportObj.settings ?= [] exportObj.settings.initiative_prefix = @misc_settings_initiative_prefix.prop('checked') if @backend? if @misc_settings_initiative_prefix.prop('checked') @backend.set 'showInitiativeInFrontOfPilotName', '1', (ds) => @misc_settings_infoline.text "Changes Saved" @misc_settings_infoline.fadeIn 100, => @misc_settings_infoline.fadeOut 3000 else @backend.deleteSetting 'showInitiativeInFrontOfPilotName', (dd) => @misc_settings_infoline.text "Changes Saved" @misc_settings_infoline.fadeIn 100, => @misc_settings_infoline.fadeOut 3000 @misc_settings.click (e) => e.preventDefault() @misc_settings_modal.modal() @misc_settings_initiative_prefix.prop('checked', exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix) @choose_obstacles_modal = $ document.createElement 'DIV' @choose_obstacles_modal.addClass 'modal fade choose-obstacles-modal' @choose_obstacles_modal.tabindex = "-1" @choose_obstacles_modal.role = "dialog" @container.append @choose_obstacles_modal @choose_obstacles_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <label class='choose-obstacles-description'>Choose up to three obstacles, to include in the permalink for use in external programs</label> </div> <div class="modal-body"> <div class="obstacle-select-container" style="float:left"> <select multiple class='obstacle-select' size="18"> <option class="coreasteroid0-select" value="coreasteroid0">Core Asteroid 0</option> <option class="coreasteroid1-select" value="coreasteroid1">Core Asteroid 1</option> <option class="coreasteroid2-select" value="coreasteroid2">Core Asteroid 2</option> <option class="coreasteroid3-select" value="coreasteroid3">Core Asteroid 3</option> <option class="coreasteroid4-select" value="coreasteroid4">Core Asteroid 4</option> <option class="coreasteroid5-select" value="coreasteroid5">Core Asteroid 5</option> <option class="yt2400debris0-select" value="yt2400debris0">YT2400 Debris 0</option> <option class="yt2400debris1-select" value="yt2400debris1">YT2400 Debris 1</option> <option class="yt2400debris2-select" value="yt2400debris2">YT2400 Debris 2</option> <option class="vt49decimatordebris0-select" value="vt49decimatordebris0">VT49 Debris 0</option> <option class="vt49decimatordebris1-select" value="vt49decimatordebris1">VT49 Debris 1</option> <option class="vt49decimatordebris2-select" value="vt49decimatordebris2">VT49 Debris 2</option> <option class="core2asteroid0-select" value="core2asteroid0">Force Awakens Asteroid 0</option> <option class="core2asteroid1-select" value="core2asteroid1">Force Awakens Asteroid 1</option> <option class="core2asteroid2-select" value="core2asteroid2">Force Awakens Asteroid 2</option> <option class="core2asteroid3-select" value="core2asteroid3">Force Awakens Asteroid 3</option> <option class="core2asteroid4-select" value="core2asteroid4">Force Awakens Asteroid 4</option> <option class="core2asteroid5-select" value="core2asteroid5">Force Awakens Asteroid 5</option> <option class="gascloud1-select" value="gascloud1">Gas Cloud 1</option> <option class="gascloud2-select" value="gascloud2">Gas Cloud 2</option> <option class="gascloud3-select" value="gascloud3">Gas Cloud 3</option> <option class="gascloud4-select" value="gascloud4">Gas Cloud 4</option> <option class="gascloud5-select" value="gascloud5">Gas Cloud 5</option> <option class="gascloud6-select" value="gascloud6">Gas Cloud 6</option> </select> </div> <div class="obstacle-image-container" style="display:none;"> <img class="obstacle-image" src="images/core2asteroid0.png" /> </div> </div> <div class="modal-footer d-print-none"> <button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ @obstacles_select = @choose_obstacles_modal.find('.obstacle-select') @obstacles_select_image = @choose_obstacles_modal.find('.obstacle-image-container') # Backend @backend_list_squads_button = $ @container.find('button.backend-list-my-squads') @backend_list_squads_button.click (e) => e.preventDefault() if @backend? @backend.list this @backend_save_list_button = $ @container.find('button.save-list') @backend_save_list_button.click (e) => e.preventDefault() if @backend? and not @backend_save_list_button.hasClass('disabled') additional_data = points: @total_points description: @describeSquad() cards: @listCards() notes: @notes.val().substr(0, 1024) obstacles: @getObstacles() tag: @tag.val().substr(0, 1024) @backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;Saving squad... """ @backend_status.show() @backend_save_list_button.addClass 'disabled' await @backend.save @serialize(), @current_squad.id, @current_squad.name, @faction, additional_data, defer(results) if results.success @current_squad.dirty = false if @current_squad.id? @backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;Squad updated successfully. """ else @backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;New squad saved successfully. """ @current_squad.id = results.id @container.trigger 'xwing-backend:squadDirtinessChanged' else @backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ @backend_save_list_button.removeClass 'disabled' @backend_save_list_as_button = $ @container.find('button.save-list-as') @backend_save_list_as_button.addClass 'disabled' @backend_save_list_as_button.click (e) => e.preventDefault() if @backend? and not @backend_save_list_as_button.hasClass('disabled') @backend.showSaveAsModal this @backend_delete_list_button = $ @container.find('button.delete-list') @backend_delete_list_button.click (e) => e.preventDefault() if @backend? and not @backend_delete_list_button.hasClass('disabled') @backend.showDeleteModal this content_container = $ document.createElement 'DIV' content_container.addClass 'container-fluid' @container.append content_container content_container.append $.trim """ <div class="row"> <div class="col-md-9 ship-container"> <label class="notes-container show-authenticated col-md-10"> <span class="notes-name">Squad Notes:</span> <br /> <textarea class="squad-notes"></textarea> <br /> <span class="tag-name">Tag:</span> <input type="search" class="squad-tag"></input> </label> <div class="obstacles-container"> <button class="btn btn-info choose-obstacles"><i class="fa fa-cloud"></i>&nbsp;Choose Obstacles</button> </div> </div> <div class="col-md-3 info-container" id="info-container"> </div> </div> """ @ship_container = $ content_container.find('div.ship-container') @info_container = $ content_container.find('div.info-container') @obstacles_container = content_container.find('.obstacles-container') @notes_container = $ content_container.find('.notes-container') @notes = $ @notes_container.find('textarea.squad-notes') @tag = $ @notes_container.find('input.squad-tag') @info_container.append $.trim @createInfoContainerUI() @info_container.hide() @print_list_button = $ @container.find('button.print-list') @container.find('[rel=tooltip]').tooltip() # obstacles @obstacles_button = $ @container.find('button.choose-obstacles') @obstacles_button.click (e) => e.preventDefault() @showChooseObstaclesModal() # conditions @condition_container = $ document.createElement('div') @condition_container.addClass 'conditions-container d-flex flex-wrap' @container.append @condition_container @mobile_tooltip_modal = $ document.createElement 'DIV' @mobile_tooltip_modal.addClass 'modal fade choose-obstacles-modal d-print-none' @mobile_tooltip_modal.tabindex = "-1" @mobile_tooltip_modal.role = "dialog" @container.append @mobile_tooltip_modal @mobile_tooltip_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> </div> <div class="modal-body"> """ + @createInfoContainerUI() + """ </div> <div class="modal-footer"> <button class="btn btn-danger close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> </div> """ createInfoContainerUI: -> return """ <div class="card info-well"> <div class="info-name"></div> <div class="info-type"></div> <span class="info-collection"></span> <table class="table-sm"> <tbody> <tr class="info-ship"> <td class="info-header">Ship</td> <td class="info-data"></td> </tr> <tr class="info-base"> <td class="info-header">Base</td> <td class="info-data"></td> </tr> <tr class="info-skill"> <td class="info-header">Initiative</td> <td class="info-data info-skill"></td> </tr> <tr class="info-engagement"> <td class="info-header">Engagement</td> <td class="info-data info-engagement"></td> </tr> <tr class="info-attack-bullseye"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-fullfront"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-left"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-leftarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-right"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-rightarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-back"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-turret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-doubleturret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-agility"> <td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td> <td class="info-data info-agility"></td> </tr> <tr class="info-hull"> <td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td> <td class="info-data info-hull"></td> </tr> <tr class="info-shields"> <td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td> <td class="info-data info-shields"></td> </tr> <tr class="info-force"> <td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td> <td class="info-data info-force"></td> </tr> <tr class="info-charge"> <td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td> <td class="info-data info-charge"></td> </tr> <tr class="info-energy"> <td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td> <td class="info-data info-energy"></td> </tr> <tr class="info-range"> <td class="info-header">Range</td> <td class="info-data info-range"></td><td class="info-rangebonus"><i class="xwing-miniatures-font red header-range xwing-miniatures-font-rangebonusindicator"></i></td> </tr> <tr class="info-actions"> <td class="info-header">Actions</td> <td class="info-data"></td> </tr> <tr class="info-upgrades"> <td class="info-header">Upgrades</td> <td class="info-data"></td> </tr> </tbody> </table> <p class="info-restrictions"></p> <p class="info-text"></p> <p class="info-maneuvers"></p> <br /> <span class="info-header info-sources">Sources:</span> <span class="info-data info-sources"></span> </div> """ setupEventHandlers: -> @container.on 'xwing:claimUnique', (e, unique, type, cb) => @claimUnique unique, type, cb .on 'xwing:releaseUnique', (e, unique, type, cb) => @releaseUnique unique, type, cb .on 'xwing:pointsUpdated', (e, cb=$.noop) => if @isUpdatingPoints cb() else @isUpdatingPoints = true @onPointsUpdated () => @isUpdatingPoints = false cb() .on 'xwing-backend:squadLoadRequested', (e, squad, cb=$.noop) => @onSquadLoadRequested squad cb() .on 'xwing-backend:squadDirtinessChanged', (e) => @onSquadDirtinessChanged() .on 'xwing-backend:squadNameChanged', (e) => @onSquadNameChanged() .on 'xwing:beforeLanguageLoad', (e, cb=$.noop) => @pretranslation_serialized = @serialize() cb() .on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) => if @language != language @language = language old_dirty = @current_squad.dirty if @pretranslation_serialized.length? @loadFromSerialized @pretranslation_serialized for ship in @ships ship.updateSelections() @current_squad.dirty = old_dirty @pretranslation_serialized = undefined cb() # Recently moved this here. Did this ever work? .on 'xwing:shipUpdated', (e, cb=$.noop) => all_allocated = true for ship in @ships ship.updateSelections() if ship.ship_selector.val() == '' all_allocated = false #console.log "all_allocated is #{all_allocated}, suppress_automatic_new_ship is #{@suppress_automatic_new_ship}" #console.log "should we add ship: #{all_allocated and not @suppress_automatic_new_ship}" @addShip() if all_allocated and not @suppress_automatic_new_ship $(window).on 'xwing-backend:authenticationChanged', (e) => @resetCurrentSquad() .on 'xwing-collection:created', (e, collection) => # console.log "#{@faction}: collection was created" @collection = collection # console.log "#{@faction}: Collection created, checking squad" @collection.onLanguageChange null, @language @checkCollection() @collection_button.removeClass 'd-none' .on 'xwing-collection:changed', (e, collection) => # console.log "#{@faction}: Collection changed, checking squad" @checkCollection() .on 'xwing-collection:destroyed', (e, collection) => @collection = null @collection_button.addClass 'd-none' .on 'xwing:pingActiveBuilder', (e, cb) => cb(this) if @container.is(':visible') .on 'xwing:activateBuilder', (e, faction, cb) => if faction == @faction @tab.tab('show') cb this .on 'xwing:gameTypeChanged', (e, gameType, cb=$.noop) => @onGameTypeChanged gameType, cb if @game_type_selector.val() != gameType @game_type_selector.val(gameType).trigger('change') @obstacles_select.change (e) => if @obstacles_select.val().length > 3 @obstacles_select.val(@current_squad.additional_data.obstacles) else previous_obstacles = @current_squad.additional_data.obstacles @current_obstacles = (o for o in @obstacles_select.val()) if (previous_obstacles?) new_selection = @current_obstacles.filter((element) => return previous_obstacles.indexOf(element) == -1) else new_selection = @current_obstacles if new_selection.length > 0 @showChooseObstaclesSelectImage(new_selection[0]) @current_squad.additional_data.obstacles = @current_obstacles @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' @container.trigger 'xwing:pointsUpdated' @view_list_button.click (e) => e.preventDefault() @showTextListModal() @print_list_button.click (e) => e.preventDefault() # Copy text list to printable @printable_container.find('.printable-header').html @list_modal.find('.modal-header').html() @printable_container.find('.printable-body').text '' switch @list_display_mode when 'simple' @printable_container.find('.printable-body').html @simple_container.html() else for ship in @ships @printable_container.find('.printable-body').append ship.toHTML() if ship.pilot? @printable_container.find('.fancy-ship').toggleClass 'tall', @list_modal.find('.toggle-vertical-space').prop('checked') @printable_container.find('.printable-body').toggleClass 'bw', not @list_modal.find('.toggle-color-print').prop('checked') if @list_modal.find('.toggle-skip-text-print').prop('checked') for text in @printable_container.find('.upgrade-text, .fancy-pilot-text') text.hidden = true if @list_modal.find('.toggle-maneuver-print').prop('checked') @printable_container.find('.printable-body').append @getSquadDialsAsHTML() expanded_hull_and_shield = @list_modal.find('.toggle-expanded-shield-hull-print').prop('checked') for container in @printable_container.find('.expanded-hull-or-shield') container.hidden = not expanded_hull_and_shield for container in @printable_container.find('.simple-hull-or-shield') container.hidden = expanded_hull_and_shield faction = switch @faction when 'Rebel Alliance' 'rebel' when 'Galactic Empire' 'empire' when 'Scum and Villainy' 'scum' when 'Resistance' 'rebel-outline' when 'First Order' 'firstorder' when 'Galactic Republic' 'republic' when 'Separatist Alliance' 'separatists' when 'All' 'first-player-4' @printable_container.find('.squad-faction').html """<i class="xwing-miniatures-font xwing-miniatures-font-#{faction}"></i>""" # List type if @isHyperspace @printable_container.find('.squad-name').append """ <i class="xwing-miniatures-font xwing-miniatures-font-first-player-1"></i>""" if @isEpic @printable_container.find('.squad-name').append """ <i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>""" # Notes, if present @printable_container.find('.printable-body').append $.trim """ <div class="version">Points Version: 1.9.0 March 2021</div> """ if $.trim(@notes.val()) != '' @printable_container.find('.printable-body').append $.trim """ <h5 class="print-notes">Notes:</h5> <pre class="print-notes"></pre> """ @printable_container.find('.printable-body pre.print-notes').text @notes.val() else # Conditions @printable_container.find('.printable-body').append $.trim """ <div class="print-conditions"></div> """ @printable_container.find('.printable-body .print-conditions').html @condition_container.html() # Obstacles if @list_modal.find('.toggle-obstacles').prop('checked') @printable_container.find('.printable-body').append $.trim """ <div class="obstacles"> <div>Mark the three obstacles you are using.</div> <img class="obstacle-silhouettes" src="images/xws-obstacles.png" /> </div> """ # Add List Juggler QR code query = @getPermaLinkParams(['sn', 'obs']) if query? and @list_modal.find('.toggle-juggler-qrcode').prop('checked') @printable_container.find('.printable-body').append $.trim """ <div class="qrcode-container"> <div class="permalink-container"> <div class="qrcode"></div> <div class="qrcode-text">Scan to open this list in the builder</div> </div> <div class="juggler-container"> <div class="qrcode"></div> <div class="qrcode-text">For List Juggler (When it's updated for 2.0)</div> </div> </div> """ text = "https://yasb-xws.herokuapp.com/juggler#{query}" @printable_container.find('.juggler-container .qrcode').qrcode render: 'div' ec: 'M' size: if text.length < 144 then 144 else 160 text: text text = "https://raithos.github.io/#{query}" @printable_container.find('.permalink-container .qrcode').qrcode render: 'div' ec: 'M' size: if text.length < 144 then 144 else 160 text: text window.print() $(window).resize => @select_simple_view_button.click() if $(window).width() < 768 and @list_display_mode != 'simple' for ship in @ships ship.checkPilotSelectorQueryModal() @notes.change @onNotesUpdated @tag.change @onNotesUpdated @notes.on 'keyup', @onNotesUpdated @tag.on 'keyup', @onNotesUpdated getPermaLinkParams: (ignored_params=[]) => params = {} params.f = encodeURI(@faction) unless 'f' in ignored_params params.d = encodeURI(@serialize()) unless 'd' in ignored_params params.sn = encodeURIComponent(@current_squad.name) unless 'sn' in ignored_params params.obs = encodeURI(@current_squad.additional_data.obstacles || '') unless 'obs' in ignored_params return "?" + ("#{k}=#{v}" for k, v of params).join("&") getPermaLink: (params=@getPermaLinkParams()) => "#{URL_BASE}#{params}" updatePermaLink: () => return unless @container.is(':visible') # gross but couldn't make clearInterval work next_params = @getPermaLinkParams() if window.location.search != next_params window.history.replaceState(next_params, '', @getPermaLink(next_params)) onNotesUpdated: => if @total_points > 0 @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' onGameTypeChanged: (gametype, cb=$.noop) => oldHyperspace = @isHyperspace oldEpic = @isEpic oldQuickbuild = @isQuickbuild @isHyperspace = false @isEpic = false @isQuickbuild = false switch gametype when 'standard' @desired_points_input.val 200 when 'hyperspace' @isHyperspace = true @desired_points_input.val 200 when 'epic' @isEpic = true @desired_points_input.val 500 when 'quickbuild' @isQuickbuild = true @desired_points_input.val 8 if oldQuickbuild != @isQuickbuild old_id = @current_squad.id @newSquadFromScratch($.trim(@current_squad.name)) @current_squad.id = old_id # we want to keep the ID, so we allow people to use the save button else old_id = @current_squad.id @container.trigger 'xwing:pointsUpdated', $.noop @container.trigger 'xwing:shipUpdated' cb() addStandardizedToList: (ship) -> if ship.data?.name? idx = @standard_list['Ship'].indexOf ship.data.name if idx > -1 for ship_upgrade in ship.upgrades if ship_upgrade.slot == @standard_list['Upgrade'][idx].slot ship_upgrade.setData @standard_list['Upgrade'][idx] break onPointsUpdated: (cb=$.noop) => tot_points = 0 points_dest = 0 unreleased_content_used = false # validating may remove the ship, if not only some upgrade, but the pilot himself is not valid. Thus iterate backwards over the array, so that is probably fine? for i in [@ships.length - 1 ... -1] ship = @ships[i] ship.validate() continue unless ship # if the ship has been removed, we no longer care about it # Standardized Loop, will integrate later for efficiency @addStandardizedToList(ship) tot_points += ship.getPoints() if ship.destroystate == 1 points_dest += Math.ceil ship.getPoints() / 2 else if ship.destroystate == 2 points_dest += ship.getPoints() ship_uses_unreleased_content = ship.checkUnreleasedContent() unreleased_content_used = ship_uses_unreleased_content if ship_uses_unreleased_content @total_points = tot_points @points_destroyed = points_dest @total_points_span.text @total_points points_left = parseInt(@desired_points_input.val()) - @total_points points_destroyed = parseInt(@total_points) @points_remaining_span.text points_left @points_destroyed_span.html if points_dest != 0 then """<i class="xwing-miniatures-font xwing-miniatures-font-hit"></i>#{points_dest}""" else "" @points_remaining_container.toggleClass 'red', (points_left < 0) @unreleased_content_used_container.toggleClass 'd-none', not unreleased_content_used @fancy_total_points_container.text @total_points # update text list @fancy_container.text '' @simple_container.html '<table class="simple-table"></table>' simplecopy_ships = [] reddit_ships = [] tts_ships = [] bbcode_ships = [] htmlview_ships = [] for ship in @ships if ship.pilot? @fancy_container.append ship.toHTML() #for dial in @fancy_container.find('.fancy-dial') #dial.hidden = true @simple_container.find('table').append ship.toTableRow() simplecopy_ships.push ship.toSimpleCopy() reddit_ships.push ship.toRedditText() tts_ships.push ship.toTTSText() bbcode_ships.push ship.toBBCode() htmlview_ships.push ship.toSimpleHTML() @htmlview_container.find('textarea').val $.trim """#{htmlview_ships.join '<br />'} <br /> <b><i>Total: #{@total_points}</i></b> <br /> <a href="#{@getPermaLink()}">View in Yet Another Squad Builder 2.0</a> """ @reddit_container.find('textarea').val $.trim """#{reddit_ships.join " \n"} \n**Total:** *#{@total_points}* \n \n[View in Yet Another Squad Builder 2.0](#{@getPermaLink()})""" @simplecopy_container.find('textarea').val $.trim """#{simplecopy_ships.join ""} \nTotal: #{@total_points} \n \nView in Yet Another Squad Builder 2.0: #{@getPermaLink()}""" #Additional code to add obstacles to TTS obstacles = @getObstacles() if (obstacles? and obstacles.length > 0) and (tts_ships.length > 0) tts_ships[tts_ships.length - 1] = tts_ships[tts_ships.length - 1].slice(0, -2) tts_obstacles = ' |' for obstacle in obstacles if obstacle? tts_obstacles += """ #{obstacle} /""" tts_obstacles = tts_obstacles.slice(0, -1) tts_ships.push tts_obstacles @tts_textarea.val $.trim """#{tts_ships.join ""}""" @bbcode_container.find('textarea').val $.trim """#{bbcode_ships.join "\n\n"}\n[b][i]Total: #{@total_points}[/i][/b]\n\n[url=#{@getPermaLink()}]View in Yet Another Squad Builder 2.0[/url]""" # console.log "#{@faction}: Squad updated, checking collection" @checkCollection() # update conditions used # this old version of phantomjs i'm using doesn't support Set if Set? conditions_set = new Set() for ship in @ships # shouldn't there be a set union ship.getConditions().forEach (condition) -> conditions_set.add(condition) conditions = [] conditions_set.forEach (condition) -> conditions.push(condition) conditions.sort (a, b) -> if a.name.canonicalize() < b.name.canonicalize() -1 else if b.name.canonicalize() > a.name.canonicalize() 1 else 0 @condition_container.text '' conditions.forEach (condition) => @condition_container.append conditionToHTML(condition) cb @total_points onSquadLoadRequested: (squad) => # console.log(squad.additional_data.obstacles) @current_squad = squad @backend_delete_list_button.removeClass 'disabled' @squad_name_input.val @current_squad.name @squad_name_placeholder.text @current_squad.name @current_obstacles = @current_squad.additional_data.obstacles @updateObstacleSelect(@current_squad.additional_data.obstacles) if squad.serialized.length? @loadFromSerialized squad.serialized @notes.val(squad.additional_data.notes ? '') @tag.val(squad.additional_data.tag ? '') @backend_status.fadeOut 'slow' @current_squad.dirty = false @container.trigger 'xwing-backend:squadDirtinessChanged' @container.trigger 'xwing-backend:squadNameChanged' onSquadDirtinessChanged: () => @current_squad.name = $.trim(@squad_name_input.val()) @backend_save_list_button.toggleClass 'disabled', not (@current_squad.dirty and @total_points > 0) @backend_save_list_as_button.toggleClass 'disabled', @total_points == 0 @backend_delete_list_button.toggleClass 'disabled', not @current_squad.id? if @ships.length > 1 $('meta[property="og:description"]').attr("content", "X-Wing Squadron by YASB 2.0: " + @current_squad.name + ": " + @describeSquad()) else $('meta[property="og:description"]').attr("content", "YASB 2.0 is a simple, fast, and easy to use squad builder for X-Wing Miniatures by Fantasy Flight Games.") # Moved XWS update to whenever the dirtyness changed rather than on points updated. @xws_textarea.val $.trim JSON.stringify(@toXWS()) $('#xws-qrcode-container').text '' $('#xws-qrcode-container').qrcode render: 'canvas' text: JSON.stringify(@toMinimalXWS()) ec: 'L' size: 128 onSquadNameChanged: () => if @current_squad.name.length > SQUAD_DISPLAY_NAME_MAX_LENGTH short_name = "#{@current_squad.name.substr(0, SQUAD_DISPLAY_NAME_MAX_LENGTH)}&hellip;" else short_name = @current_squad.name @squad_name_placeholder.text '' @squad_name_placeholder.append short_name @squad_name_input.val @current_squad.name return unless $.getParameterByName('f') == @faction if @current_squad.name != "Unnamed Squadron" and @current_squad.name != "Unsaved Squadron" if (document.title != "YASB 2.0 - " + @current_squad.name) document.title = "YASB 2.0 - " + @current_squad.name else document.title = "YASB 2.0" removeAllShips: -> while @ships.length > 0 @removeShip @ships[0] throw new Error("Ships not emptied") if @ships.length > 0 showTextListModal: -> # Display print/text view modal @list_modal.modal 'show' showXWSModal: (xws) -> # Display xws view modal @select_xws_view() @showTextListModal() showChooseObstaclesModal: -> @obstacles_select.val(@current_squad.additional_data.obstacles) @choose_obstacles_modal.modal 'show' showChooseObstaclesSelectImage: (obstacle) -> @image_name = 'images/' + obstacle + '.png' @obstacles_select_image.find('.obstacle-image').attr 'src', @image_name @obstacles_select_image.show() updateObstacleSelect: (obstacles) -> @current_obstacles = obstacles @obstacles_select.val(obstacles) serialize: -> serialization_version = 8 game_type_abbrev = switch @game_type_selector.val() when 'standard' 's' when 'hyperspace' 'h' when 'epic' 'e' when 'quickbuild' 'q' selected_points = $.trim @desired_points_input.val() """v#{serialization_version}Z#{game_type_abbrev}Z#{selected_points}Z#{( ship.toSerialized() for ship in @ships when ship.pilot? and (not @isQuickbuild or ship.primary) ).join 'Y'}""" changeGameTypeOnSquadLoad: (gametype) -> if @game_type_selector.val() != gametype $(window).trigger 'xwing:gameTypeChanged', gametype loadFromSerialized: (serialized) -> @suppress_automatic_new_ship = true # Clear all existing ships @removeAllShips() re = if "Z" in serialized then /^v(\d+)Z(.*)/ else /^v(\d+)!(.*)/ matches = re.exec serialized if matches? # versioned version = parseInt matches[1] # version 1-3 are 1st edition only (may be removed here) # version 4 is the final version of 1st edition x-wing, and has been the first few weeks of YASB 2.0 # version 5 is the first version for 2nd edtition x-wing only, it features extended (=standard), hyperspace, quickbuild and custom mode # version 6 has the only difference to version 5 is, that custom (=extended with != 200 points) has been removed and points are specified for all modes. # version 7 has arbitrary ordering of upgrades additionally supported # version 8 is the current version, replacing "!" with "Z" in the serialzed string, and 'Y' etc ship_splitter = if version > 7 then 'Y' else ';' # parse out game type [ game_type_abbrev, desired_points, serialized_ships ] = if version > 7 [g, p, s] = matches[2].split('Z') [g, parseInt(p), s] else [ game_type_and_point_abbrev, s ] = matches[2].split('!') if parseInt(game_type_and_point_abbrev.split('=')[1]) p = parseInt(game_type_and_point_abbrev.split('=')[1]) else p = 200 g = game_type_and_point_abbrev.split('=')[0] [ g, p, s ] # check if there are serialized ships to load if !serialized_ships? # something went wrong, we can't load that serialization @loading_failed_container.toggleClass 'd-none', false return switch game_type_abbrev when 's' @changeGameTypeOnSquadLoad 'standard' when 'h' @changeGameTypeOnSquadLoad 'hyperspace' when 'e' @changeGameTypeOnSquadLoad 'epic' when 'q' @changeGameTypeOnSquadLoad 'quickbuild' @desired_points_input.val desired_points @desired_points_input.change() ships_with_unmet_dependencies = [] if serialized_ships.length? for serialized_ship in serialized_ships.split(ship_splitter) unless serialized_ship == '' new_ship = @addShip() # try to create ship. fromSerialized returns false, if some upgrade have been skipped as they are not legal until now (e.g. 0-0-0 but vader is not yet in the squad) # if not the entire ship is valid, we'll try again later - but keep the valid part added, so other ships may already see some upgrades if (not new_ship.fromSerialized version, serialized_ship) or not new_ship.pilot # also check, if the pilot has been set (the pilot himself was not invalid) ships_with_unmet_dependencies.push [new_ship, serialized_ship] for ship in ships_with_unmet_dependencies # 2nd attempt to load ships with unmet dependencies. if not ship[0].pilot # create ship, if the ship was so invalid, that it in fact decided to not exist ship[0] = @addShip() ship[0].fromSerialized version, ship[1] @suppress_automatic_new_ship = false # Finally, the unassigned ship @addShip() select_xws_view: () -> @select_xws_view_button.blur() unless @list_display_mode == 'xws' @list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse' @select_xws_view_button.addClass 'btn-inverse' @list_display_mode = 'xws' @xws_container.show() @bbcode_container.hide() @htmlview_container.hide() @simple_container.hide() @simplecopy_container.hide() @reddit_container.hide() @fancy_container.hide() @tts_container.hide() @xws_textarea.select() @xws_textarea.focus() @toggle_vertical_space_container.hide() @toggle_color_print_container.hide() @toggle_color_skip_text.hide() @toggle_maneuver_dial_container.hide() @toggle_expanded_shield_hull_container.hide() @toggle_qrcode_container.hide() @toggle_obstacle_container.hide() @btn_print_list.disabled = true; uniqueIndex: (unique, type) -> if type not of @uniques_in_use throw new Error("Invalid unique type '#{type}'") @uniques_in_use[type].indexOf unique claimUnique: (unique, type, cb) => if @uniqueIndex(unique, type) < 0 # Claim pilots with the same canonical name for other in (exportObj.pilotsByUniqueName[unique.canonical_name.getXWSBaseName()] or []) if unique != other if @uniqueIndex(other, 'Pilot') < 0 # console.log "Also claiming unique pilot #{other.canonical_name} in use" @uniques_in_use['Pilot'].push other else throw new Error("Unique #{type} '#{unique.name}' already claimed as pilot") # Claim other upgrades with the same canonical name for otherslot, bycanonical of exportObj.upgradesBySlotUniqueName for canonical, other of bycanonical if canonical.getXWSBaseName() == unique.canonical_name.getXWSBaseName() and unique != other if @uniqueIndex(other, 'Upgrade') < 0 # console.log "Also claiming unique #{other.canonical_name} (#{otherslot}) in use" @uniques_in_use['Upgrade'].push other # else # throw new Error("Unique #{type} '#{unique.name}' already claimed as #{otherslot}") # Solitary Check if unique.solitary? @uniques_in_use['Slot'].push unique.slot @uniques_in_use[type].push unique else throw new Error("Unique #{type} '#{unique.name}' already claimed") cb() releaseUnique: (unique, type, cb) => idx = @uniqueIndex(unique, type) if idx >= 0 # Release all uniques with the same canonical name and base name for type, uniques of @uniques_in_use # Removing stuff in a loop sucks, so we'll construct a new list if type == 'Slot' if unique.solitary? @uniques_in_use[type] = [] for u in uniques if u != unique.slot # Keep this one @uniques_in_use[type].push u.slot else @uniques_in_use[type] = [] for u in uniques if u.canonical_name.getXWSBaseName() != unique.canonical_name.getXWSBaseName() # Keep this one @uniques_in_use[type].push u # else # console.log "Releasing #{u.name} (#{type}) with canonical name #{unique.canonical_name}" else throw new Error("Unique #{type} '#{unique.name}' not in use") cb() addShip: -> new_ship = new Ship builder: this container: @ship_container @ships.push new_ship @ship_number_invalid_container.toggleClass 'd-none', (@ships.length < 10 and @ships.length > 2) # bounds are 2..10 as we always have a "empty" ship at the bottom @multi_faction_warning_container.toggleClass 'd-none', (@faction != "All") new_ship removeShip: (ship, cb=$.noop) -> if ship?.destroy? await ship.destroy defer() await @container.trigger 'xwing:pointsUpdated', defer() @current_squad.dirty = true @container.trigger 'xwing-backend:squadDirtinessChanged' @ship_number_invalid_container.toggleClass 'd-none', (@ships.length < 10 and @ships.length > 2) @multi_faction_warning_container.toggleClass 'd-none', (@faction != "All") cb() matcher: (item, term) -> item.toUpperCase().indexOf(term.toUpperCase()) >= 0 isOurFaction: (faction, alt_faction = '') -> check_faction = @faction if @faction == "All" if alt_faction != '' check_faction = alt_faction else return true if faction instanceof Array for f in faction if getPrimaryFaction(f) == check_faction return true false else getPrimaryFaction(faction) == check_faction isItemAvailable: (item_data, shipCheck=false) -> # this method is not even invoked by most quickbuild stuff to check availability for quickbuild squads, as the method was formerly just telling apart extended/hyperspace if @isQuickbuild return true else if @isHyperspace return exportObj.hyperspaceCheck(item_data, @faction, shipCheck) else if (not @isEpic) return exportObj.epicExclusions(item_data) else return true getAvailableShipsMatching: (term='',sorted = true, collection_only = false) -> ships = [] for ship_name, ship_data of exportObj.ships if @isOurFaction(ship_data.factions) and (@matcher(ship_data.name, term) or (ship_data.display_name and @matcher(ship_data.display_name, term))) if (@isItemAvailable(ship_data, true)) if (not collection_only or (@collection? and (@collection.checks.collectioncheck == "true") and @collection.checkShelf('ship', ship_data.name))) ships.push id: ship_data.name text: if ship_data.display_name then ship_data.display_name else ship_data.name name: ship_data.name display_name: ship_data.display_name canonical_name: ship_data.canonical_name xws: ship_data.xws icon: if ship_data.icon then ship_data.icon else ship_data.xws if sorted ships.sort exportObj.sortHelper return ships getAvailableShipsMatchingAndCheapEnough: (points, term='', sorted=false, collection_only = false) -> # returns a list of ships that have at least one pilot cheaper than the given points value possible_ships = @getAvailableShipsMatching(term, sorted, collection_only) cheap_ships = [] for ship in possible_ships pilots = @getAvailablePilotsForShipIncluding(ship.name, null, '', true) if pilots.length and pilots[0].points <= points cheap_ships.push(ship) return cheap_ships getAvailablePilotsForShipIncluding: (ship, include_pilot, term='', sorted = true, ship_selector = null) -> # Returns data formatted for Select2 retval = [] if not @isQuickbuild # select available pilots according to ususal pilot selection available_faction_pilots = (pilot for pilot_name, pilot of exportObj.pilots when (not ship? or pilot.ship == ship) and @isOurFaction(pilot.faction) and (@matcher(pilot_name, term) or (pilot.display_name and @matcher(pilot.display_name, term)) ) and (@isItemAvailable(pilot, true))) eligible_faction_pilots = (pilot for pilot_name, pilot of available_faction_pilots when (not pilot.unique? or pilot not in @uniques_in_use['Pilot'] or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()) and (not pilot.max_per_squad? or @countPilots(pilot.canonical_name) < pilot.max_per_squad or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()) and (not pilot.restriction_func? or pilot.restriction_func((builder: @) , pilot))) # Re-add selected pilot if include_pilot? and include_pilot.unique? and (@matcher(include_pilot.name, term) or (include_pilot.display_name and @matcher(include_pilot.display_name, term)) ) eligible_faction_pilots.push include_pilot retval = ({ id: pilot.id, text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then pilot.skill + ' - ' else ''}#{if pilot.display_name then pilot.display_name else pilot.name} (#{pilot.points})", points: pilot.points, ship: pilot.ship, name: pilot.name, display_name: pilot.display_name, disabled: pilot not in eligible_faction_pilots } for pilot in available_faction_pilots) else # select according to quickbuild cards # filter for faction and ship quickbuilds_matching_ship_and_faction = (quickbuild for id, quickbuild of exportObj.quickbuildsById when (not ship? or quickbuild.ship == ship) and @isOurFaction(quickbuild.faction) and (@matcher(quickbuild.pilot, term) or (exportObj.pilots[quickbuild.pilot].display_name? and @matcher(exportObj.pilots[quickbuild.pilot].display_name, term)) )) # create a list of the uniques belonging to the currently selected pilot uniques_in_use_by_pilot_in_use = [] if include_pilot? and include_pilot != -1 include_quickbuild = exportObj.quickbuildsById[include_pilot] include_pilot_pilot = exportObj.pilots[include_quickbuild.pilot] if include_pilot_pilot.unique? uniques_in_use_by_pilot_in_use.push include_pilot_pilot for other in (exportObj.pilotsByUniqueName[include_pilot_pilot.canonical_name.getXWSBaseName()] or []) if other? uniques_in_use_by_pilot_in_use.push other for include_upgrade_name in include_quickbuild.upgrades ? [] include_upgrade = exportObj.upgrades[include_upgrade_name] if include_upgrade.unique? uniques_in_use_by_pilot_in_use.push other for other in (exportObj.pilotsByUniqueName[include_upgrade.canonical_name.getXWSBaseName()] or []) if other? uniques_in_use_by_pilot_in_use.push other if include_upgrade.solitary? uniques_in_use_by_pilot_in_use.push include_upgrade.slot # we should also add upgrades with the same unique name like some selected upgrades or the pilot. However, finding them is teadious # we should also add uniques used by a linked ship. however, while it is easy to allow selecting them, it is harder to properly add them - as one need to make sure the order of selecting ship + linked ship matters # filter for uniques in use allowed_quickbuilds_containing_uniques_in_use = [] loop: for id, quickbuild of quickbuilds_matching_ship_and_faction if exportObj.pilots[quickbuild.pilot]?.unique? and exportObj.pilots[quickbuild.pilot] in @uniques_in_use.Pilot and not (exportObj.pilots[quickbuild.pilot] in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id continue if exportObj.pilots[quickbuild.pilot]?.max_per_squad? and @countPilots(exportObj.pilots[quickbuild.pilot].canonical_name) >= exportObj.pilots[quickbuild.pilot].max_per_squad and not (exportObj.pilots[quickbuild.pilot] in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id continue if quickbuild.upgrades? for upgrade in quickbuild.upgrades upgradedata = exportObj.upgrades[upgrade] if not upgradedata? console.log("There was an Issue including the upgrade " + upgrade + " in some quickbuild. Please report that Issue!") continue if upgradedata.unique? and upgradedata in @uniques_in_use.Upgrade and not (upgradedata in uniques_in_use_by_pilot_in_use) # check, if unique is used by this ship or it's linked ship if ship_selector == null or not (upgrade in exportObj.quickbuildsById[ship_selector.quickbuildId].upgrades or (ship_selector.linkedShip and upgrade in (exportObj.quickbuildsById[ship_selector.linkedShip?.quickbuildId].upgrades ? []))) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id break # check if solitary type is already claimed if upgradedata.solitary? and upgradedata.slot in @uniques_in_use['Slot'] and not (upgradedata.slot in uniques_in_use_by_pilot_in_use) allowed_quickbuilds_containing_uniques_in_use.push quickbuild.id break retval = ({id: quickbuild.id, text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then exportObj.pilots[quickbuild.pilot].skill + ' - ' else ''}#{if exportObj.pilots[quickbuild.pilot].display_name then exportObj.pilots[quickbuild.pilot].display_name else quickbuild.pilot}#{quickbuild.suffix} (#{quickbuild.threat})", points: quickbuild.threat, ship: quickbuild.ship, disabled: quickbuild.id in allowed_quickbuilds_containing_uniques_in_use} for quickbuild in quickbuilds_matching_ship_and_faction) if sorted retval = retval.sort exportObj.sortHelper retval dfl_filter_func = -> true countUpgrades: (canonical_name) -> # returns number of upgrades with given canonical name equipped count = 0 for ship in @ships for upgrade in ship.upgrades if upgrade?.data?.canonical_name == canonical_name count++ count countPilots: (canonical_name) -> # returns number of pilots with given canonical name count = 0 for ship in @ships if ship?.pilot?.canonical_name.getXWSBaseName() == canonical_name.getXWSBaseName() count++ count isShip: (ship, name) -> # console.log "returning #{f} #{name}" if ship instanceof Array for f in ship if f == name return true false else ship == name getAvailableUpgradesIncluding: (slot, include_upgrade, ship, this_upgrade_obj, term='', filter_func=@dfl_filter_func, sorted=true) -> # Returns data formatted for Select2 upgrades_in_use = (upgrade.data for upgrade in ship.upgrades) available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgrades when exportObj.slotsMatching(upgrade.slot, slot) and ( @matcher(upgrade_name, term) or (upgrade.display_name and @matcher(upgrade.display_name, term)) ) and (not upgrade.ship? or @isShip(upgrade.ship, ship.data.name)) and (not upgrade.faction? or @isOurFaction(upgrade.faction, ship.pilot.faction)) and (@isItemAvailable(upgrade))) # available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgrades when exportObj.slotsMatching(upgrade.slot, slot) and ( @matcher(upgrade_name, term) or (upgrade.display_name and @matcher(upgrade.display_name, term)) ) and (not upgrade.ship? or @isShip(upgrade.ship, ship.data.name)) and (not upgrade.faction? or ((@faction != "All") and @isOurFaction(upgrade.faction)) or ((@faction == "All") and (not ship.pilot? or (ship.pilot.faction == upgrade.faction)))) and (@isItemAvailable(upgrade))) if filter_func != @dfl_filter_func available_upgrades = (upgrade for upgrade in available_upgrades when filter_func(upgrade)) eligible_upgrades = (upgrade for upgrade_name, upgrade of available_upgrades when (not upgrade.unique? or upgrade not in @uniques_in_use['Upgrade']) and (not (ship? and upgrade.restrictions?) or ship.restriction_check(upgrade.restrictions, this_upgrade_obj)) and upgrade not in upgrades_in_use and ((not upgrade.max_per_squad?) or ship.builder.countUpgrades(upgrade.canonical_name) < upgrade.max_per_squad) and (not upgrade.solitary? or (upgrade.slot not in @uniques_in_use['Slot'] or include_upgrade?.solitary?))) for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?) eligible_upgrades.removeItem equipped_upgrade # Re-enable selected upgrade if include_upgrade? and ((( @matcher(include_upgrade.name, term) or (include_upgrade.display_name and @matcher(include_upgrade.display_name, term))) ))# or current_upgrade_forcibly_removed) # available_upgrades.push include_upgrade eligible_upgrades.push include_upgrade retval = ({ id: upgrade.id, text: "#{if upgrade.display_name then upgrade.display_name else upgrade.name} (#{this_upgrade_obj.getPoints(upgrade)}#{if upgrade.pointsarray then '*' else ''})", points: this_upgrade_obj.getPoints(upgrade), name: upgrade.name, display_name: upgrade.display_name, disabled: upgrade not in eligible_upgrades } for upgrade in available_upgrades) if sorted retval = retval.sort exportObj.sortHelper # Possibly adjust the upgrade if this_upgrade_obj?adjustment_func? (this_upgrade_obj.adjustment_func(upgrade) for upgrade in retval) else retval getSquadDialsAsHTML: () -> dialHTML = "" added_dials = {} for ship in @ships if ship.pilot? # There is always one "empty" ship at the bottom of each squad, that we want to skip. maneuvers_unmodified = ship.data.maneuvers maneuvers_modified = ship.effectiveStats().maneuvers if not added_dials[ship.data.name]? or not (maneuvers_modified.toString() in added_dials[ship.data.name]) # we only want to add each dial once per ship (if two ships share a dial, add two copies of the dial) added_dials[ship.data.name] = (added_dials[ship.data.name] ? []).concat [maneuvers_modified.toString()] # save maneuver as string, as that is easier to compare than arrays (if e.g. two ships of same type, one with and one without R4 are in a squad, we add 2 dials) dialHTML += '<div class="fancy-dial">' + """<h4 class="ship-name-dial">#{if ship.data.display_name? then ship.data.display_name else ship.data.name}""" + """#{if maneuvers_modified.toString() != maneuvers_unmodified.toString() then " (upgraded)" else ""}</h4>""" + @getManeuverTableHTML(maneuvers_modified, maneuvers_unmodified) + '</div>' return """ <div class="print-dials-container"> #{dialHTML} </div> """ # dialHTML = @builder.getManeuverTableHTML(effective_stats.maneuvers, @data.maneuvers) # Converts a maneuver table for into an HTML table. getManeuverTableHTML: (maneuvers, baseManeuvers) -> if not maneuvers? or maneuvers.length == 0 return "Missing maneuver info." # Preprocess maneuvers to see which bearings are never used so we # don't render them. bearings_without_maneuvers = [0...maneuvers[0].length] for bearings in maneuvers for difficulty, bearing in bearings if difficulty > 0 bearings_without_maneuvers.removeItem bearing # console.log "bearings without maneuvers:" # console.dir bearings_without_maneuvers outTable = "<table><tbody>" for speed in [maneuvers.length - 1 .. 0] haveManeuver = false for v in maneuvers[speed] if v > 0 haveManeuver = true break continue if not haveManeuver outTable += "<tr><td>#{speed}</td>" for turn in [0 ... maneuvers[speed].length] continue if turn in bearings_without_maneuvers outTable += "<td>" if maneuvers[speed][turn] > 0 color = switch maneuvers[speed][turn] when 1 then "dodgerblue" when 2 then "white" when 3 then "red" when 4 then "purple" # we need this to change the color to b/w in case we want to print b/w maneuverClass = switch maneuvers[speed][turn] when 1 then "svg-blue-maneuver" when 2 then "svg-white-maneuver" when 3 then "svg-red-maneuver" when 4 then "svg-purple-maneuver" outTable += """<svg xmlns="http://www.w3.org/2000/svg" width="30px" height="30px" viewBox="0 0 200 200">""" outlineColor = "black" maneuverClass2 = "svg-base-maneuver" if maneuvers[speed][turn] != baseManeuvers[speed][turn] outlineColor = "DarkSlateGrey" # highlight manuevers modified by another card (e.g. R2 Astromech makes all 1 & 2 speed maneuvers green) maneuverClass2 = "svg-modified-maneuver" if speed == 0 and turn == 2 outTable += """<rect class="svg-maneuver-stop #{maneuverClass} #{maneuverClass2}" x="50" y="50" width="100" height="100" style="fill:#{color}" />""" else transform = "" className = "" switch turn when 0 # turn left linePath = "M160,180 L160,70 80,70" trianglePath = "M80,100 V40 L30,70 Z" when 1 # bank left linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(-5 -15) rotate(45 70 90)' " when 2 # straight linePath = "M100,180 L100,100 100,80" trianglePath = "M70,80 H130 L100,30 Z" when 3 # bank right linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(5 -15) rotate(-45 130 90)' " when 4 # turn right linePath = "M40,180 L40,70 120,70" trianglePath = "M120,100 V40 L170,70 Z" when 5 # k-turn/u-turn linePath = "M50,180 L50,100 C50,10 140,10 140,100 L140,120" trianglePath = "M170,120 H110 L140,180 Z" when 6 # segnor's loop left linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(0 50)'" when 7 # segnor's loop right linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(0 50)'" when 8 # tallon roll left linePath = "M160,180 L160,70 80,70" trianglePath = "M60,100 H100 L80,140 Z" when 9 # tallon roll right linePath = "M40,180 L40,70 120,70" trianglePath = "M100,100 H140 L120,140 Z" when 10 # backward left linePath = "M50,180 S50,120 120,60" trianglePath = "M120,100 V40 L170,70 Z" transform = "transform='translate(5 -15) rotate(-45 130 90)' " className = 'backwards' when 11 # backward straight linePath = "M100,180 L100,100 100,80" trianglePath = "M70,80 H130 L100,30 Z" className = 'backwards' when 12 # backward right linePath = "M150,180 S150,120 80,60" trianglePath = "M80,100 V40 L30,70 Z" transform = "transform='translate(-5 -15) rotate(45 70 90)' " className = 'backwards' outTable += $.trim """ <g class="maneuver #{className}"> <path class = 'svg-maneuver-outer #{maneuverClass} #{maneuverClass2}' stroke-width='25' fill='none' stroke='#{outlineColor}' d='#{linePath}' /> <path class = 'svg-maneuver-triangle #{maneuverClass} #{maneuverClass2}' d='#{trianglePath}' fill='#{color}' stroke-width='5' stroke='#{outlineColor}' #{transform}/> <path class = 'svg-maneuver-inner #{maneuverClass} #{maneuverClass2}' stroke-width='15' fill='none' stroke='#{color}' d='#{linePath}' /> </g> """ outTable += "</svg>" outTable += "</td>" outTable += "</tr>" outTable += "</tbody></table>" outTable formatActions: (actions,seperation,keyword=[]) -> action_icons = [] for action in actions color = "" prefix = seperation if "Droid" in keyword action = action.replace('Focus', 'Calculate') # Search and filter each type of action by its prefix and then reformat it for html if action.search('> ') != -1 action = action.replace(/> /gi, '') prefix = """ <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> """ if action.search('F-') != -1 color = "force " action = action.replace(/F-/gi, '') else if action.search('R-') != -1 color = "red " action = action.replace(/R-/gi, '') action = action.toLowerCase().replace(/[^0-9a-z]/gi, '') action_icons.push """#{prefix}<i class="xwing-miniatures-font #{color}xwing-miniatures-font-#{action}"></i>""" actionlist = action_icons.join '' return actionlist.replace(seperation,'') showTooltip: (type, data, additional_opts, container = @info_container, force_update = false) -> if data != @tooltip_currently_displaying or force_update switch type when 'Ship' # we get all pilots for the ship, to display stuff like available slots which are treated as pilot properties, not ship properties (which makes sense, as they depend on the pilot, e.g. talent or force slots) possible_inis = [] slot_types = {} # one number per slot: 0: not available for that ship. 1: always available for that ship. 2: available for some pilots on that ship. 3: slot two times availabel for that ship 4: slot one or two times available (depending on pilot) 5: slot zero to two times available 6: slot three times available (no mixed-case implemented) -1: undefined for slot of exportObj.upgradesBySlotCanonicalName slot_types[slot] = -1 for name, pilot of exportObj.pilots if pilot.ship != data.name continue if not (pilot.skill in possible_inis) possible_inis.push(pilot.skill) for slot, state of slot_types switch pilot.slots.filter((item) => item == slot).length when 1 switch state when -1 slot_types[slot] = 1 when 0 slot_types[slot] = 2 when 3 slot_types[slot] = 4 when 0 switch state when -1 slot_types[slot] = 0 when 1 slot_types[slot] = 2 when 3,4 slot_types[slot] = 5 when 2 switch state when -1 slot_types[slot] = 3 when 0,2 slot_types[slot] = 5 when 1 slot_types[slot] = 4 when 3 slot_types[slot] = 6 possible_inis.sort() container.find('.info-type').text type container.find('.info-name').html """#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" if @collection?.counts? ship_count = @collection.counts?.ship?[data.name] ? 0 container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() first = true inis = String(possible_inis[0]) for ini in possible_inis if not first inis += ", " + ini first = false container.find('tr.info-skill td.info-data').text inis container.find('tr.info-skill').show() container.find('tr.info-engagement').hide() container.find('tr.info-attack td.info-data').text(data.attack) container.find('tr.info-attack-bullseye td.info-data').text(data.attackbull) container.find('tr.info-attack-fullfront td.info-data').text(data.attackf) container.find('tr.info-attack-left td.info-data').text(data.attackl) container.find('tr.info-attack-right td.info-data').text(data.attackr) container.find('tr.info-attack-back td.info-data').text(data.attackb) container.find('tr.info-attack-turret td.info-data').text(data.attackt) container.find('tr.info-attack-doubleturret td.info-data').text(data.attackdt) container.find('tr.info-attack').toggle(data.attack?) container.find('tr.info-attack-bullseye').toggle(data.attackbull?) container.find('tr.info-attack-fullfront').toggle(data.attackf?) container.find('tr.info-attack-left').toggle(data.attackl?) container.find('tr.info-attack-right').toggle(data.attackr?) container.find('tr.info-attack-back').toggle(data.attackb?) container.find('tr.info-attack-turret').toggle(data.attackt?) container.find('tr.info-attack-doubleturret').toggle(data.attackdt?) container.find('tr.info-ship').hide() if data.large? container.find('tr.info-base td.info-data').text "Large" else if data.medium? container.find('tr.info-base td.info-data').text "Medium" else if data.huge? container.find('tr.info-base td.info-data').text "Huge" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(data.attack_icon ? 'xwing-miniatures-font-attack') container.find('tr.info-range').hide() container.find('tr.info-agility td.info-data').text(data.agility) container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text(data.hull) container.find('tr.info-hull').show() recurringicon = '' if data.shieldrecurr? count = 0 while count < data.shieldrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-shields td.info-data').html (data.shields + recurringicon) container.find('tr.info-shields').show() recurringicon = '' if data.energyrecurr? count = 0 while count < data.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-energy td.info-data').html (data.energy + recurringicon) container.find('tr.info-energy').toggle(data.energy?) # One may want to check for force sensitive pilots and display the possible values here (like done for ini), but I'll skip this for now. container.find('tr.info-force').hide() container.find('tr.info-charge').hide() container.find('tr.info-actions td.info-data').html @formatActions(data.actions, ", ", data.keyword ? []) container.find('tr.info-actions').show() # Display all available slots, put brackets around slots that are only available for some pilots container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html(((if state == 1 then exportObj.translate(@language, 'sloticon', slot) else (if state == 2 then '('+exportObj.translate(@language, 'sloticon', slot)+')' else (if state == 3 then (exportObj.translate(@language, 'sloticon', slot) + exportObj.translate(@language, 'sloticon', slot)) else (if state == 4 then (exportObj.translate(@language, 'sloticon', slot) + '(' + exportObj.translate(@language, 'sloticon', slot) + ')') else (if state == 5 then ('(' + exportObj.translate(@language, 'sloticon', slot) + exportObj.translate(@language, 'sloticon', slot) + ')') else (if state == 6 then (exportObj.translate(@language, 'sloticon',slot) + exportObj.translate(@language, 'sloticon',slot) + exportObj.translate(@language, 'sloticon',slot)))))))) for slot, state of slot_types).join(' ') or 'None') container.find('p.info-text').hide() container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(data.maneuvers, data.maneuvers)) sources = (exportObj.translate(@language, 'sources', source) for source in data.sources).sort() container.find('.info-sources.info-data').text if (sources.length > 1) or (not ('Loose Ships' in sources)) then (if sources.length > 0 then sources.join(', ') else exportObj.translate(@language, 'ui', 'unreleased')) else "Only available from 1st edition" container.find('.info-sources').show() when 'Pilot' container.find('.info-type').text type container.find('.info-sources.info-data').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') container.find('.info-sources').show() if @collection?.counts? pilot_count = @collection.counts?.pilot?[data.name] ? 0 ship_count = @collection.counts.ship?[data.ship] ? 0 container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() # if the pilot is already selected and has uprades, some stats may be modified if additional_opts?.effectiveStats? effective_stats = additional_opts.effectiveStats() #logic to determine how many dots to use for uniqueness if data.unique? uniquedots = "&middot;&nbsp;" else if data.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" container.find('.info-name').html """#{uniquedots}#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" restriction_info = @restriction_text(data) + @upgrade_effect(data) if restriction_info != '' container.find('p.info-restrictions').html restriction_info ? '' container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html data.text ? '' container.find('p.info-text').show() ship = exportObj.ships[data.ship] container.find('tr.info-ship td.info-data').text data.ship container.find('tr.info-ship').show() if ship.large? container.find('tr.info-base td.info-data').text "Large" else if ship.medium? container.find('tr.info-base td.info-data').text "Medium" else if ship.huge? container.find('tr.info-base td.info-data').text "Huge" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() container.find('tr.info-skill td.info-data').text data.skill container.find('tr.info-skill').show() if data.engagement? container.find('tr.info-engagement td.info-data').text data.engagement container.find('tr.info-engagement').show() else container.find('tr.info-engagement').hide() # for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList # container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-attack') container.find('tr.info-attack td.info-data').text statAndEffectiveStat((data.ship_override?.attack ? ship.attack), effective_stats, 'attack') container.find('tr.info-attack').toggle(ship.attack? or effective_stats?.attack?) container.find('tr.info-attack-fullfront td.info-data').text statAndEffectiveStat((data.ship_override?.attackf ? ship.attackf), effective_stats, 'attackf') container.find('tr.info-attack-fullfront').toggle(ship.attackf? or effective_stats?.attackf?) container.find('tr.info-attack-bullseye td.info-data').text statAndEffectiveStat((data.ship_override?.attackbull ? ship.attackbull), effective_stats, 'attackbull') container.find('tr.info-attack-bullseye').toggle(ship.attackbull? or effective_stats?.attackbull?) container.find('tr.info-attack-left td.info-data').text statAndEffectiveStat((data.ship_override?.attackl ? ship.attackl), effective_stats, 'attackl') container.find('tr.info-attack-left').toggle(ship.attackl? or effective_stats?.attackl?) container.find('tr.info-attack-right td.info-data').text statAndEffectiveStat((data.ship_override?.attackr ? ship.attackr), effective_stats, 'attackr') container.find('tr.info-attack-right').toggle(ship.attackr? or effective_stats?.attackr?) container.find('tr.info-attack-back td.info-data').text statAndEffectiveStat((data.ship_override?.attackb ? ship.attackb), effective_stats, 'attackb') container.find('tr.info-attack-back').toggle(ship.attackb? or effective_stats?.attackb?) container.find('tr.info-attack-turret td.info-data').text statAndEffectiveStat((data.ship_override?.attackt ? ship.attackt), effective_stats, 'attackt') container.find('tr.info-attack-turret').toggle(ship.attackt? or effective_stats?.attackt?) container.find('tr.info-attack-doubleturret td.info-data').text statAndEffectiveStat((data.ship_override?.attackdt ? ship.attackdt), effective_stats, 'attackdt') container.find('tr.info-attack-doubleturret').toggle(ship.attackdt? or effective_stats?.attackdt?) container.find('tr.info-range').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-agility td.info-data').text statAndEffectiveStat((data.ship_override?.agility ? ship.agility), effective_stats, 'agility') container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text statAndEffectiveStat((data.ship_override?.hull ? ship.hull), effective_stats, 'hull') container.find('tr.info-hull').show() recurringicon = '' if ship.shieldrecurr? count = 0 while count < ship.shieldrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-shields td.info-data').html (statAndEffectiveStat((data.ship_override?.shields ? ship.shields), effective_stats, 'shields') + recurringicon) container.find('tr.info-shields').show() recurringicon = '' if ship.energyrecurr? count = 0 while count < ship.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count container.find('tr.info-energy td.info-data').html (statAndEffectiveStat((data.ship_override?.energy ? ship.energy), effective_stats, 'energy') + recurringicon) container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?) if (effective_stats?.force? and effective_stats.force > 0) or data.force? container.find('tr.info-force td.info-data').html (statAndEffectiveStat((data.ship_override?.force ? data.force), effective_stats, 'force') + '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').show() else container.find('tr.info-force').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').show() else container.find('tr.info-charge').hide() if effective_stats?.actions? container.find('tr.info-actions td.info-data').html @formatActions(data.ship_override?.actions ? effective_stats.actions, ", ") else container.find('tr.info-actions td.info-data').html @formatActions(data.ship_override?.actions ? ship.actions, ", ", data.keyword ? []) container.find('tr.info-actions').show() if @isQuickbuild container.find('tr.info-upgrades').hide() else container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html((exportObj.translate(@language, 'sloticon', slot) for slot in data.slots).join(' ') or 'None') container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(effective_stats?.maneuvers ? ship.maneuvers, ship.maneuvers)) when 'Quickbuild' container.find('.info-type').text 'Quickbuild' container.find('.info-sources').hide() # there are different sources for the pilot and the upgrade cards, so we won't display any container.find('.info-collection').hide() # same here, hard to give a single number telling a user how often he ownes all required cards pilot = exportObj.pilots[data.pilot] ship = exportObj.ships[data.ship] #logic to determine how many dots to use for uniqueness if pilot.unique? uniquedots = "&middot;&nbsp;" else if pilot.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" container.find('.info-name').html """#{uniquedots}#{if pilot.display_name then pilot.display_name else pilot.name}#{if data.suffix? then data.suffix else ""}#{if exportObj.isReleased(pilot) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" restriction_info = @restriction_text(data) + @upgrade_effect(data) if restriction_info != '' container.find('p.info-restrictions').html restriction_info ? '' container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html pilot.text ? '' container.find('p.info-text').show() container.find('tr.info-ship td.info-data').text data.ship container.find('tr.info-ship').show() if ship.large? container.find('tr.info-base td.info-data').text "Large" else if ship.medium? container.find('tr.info-base td.info-data').text "Medium" else container.find('tr.info-base td.info-data').text "Small" container.find('tr.info-base').show() container.find('tr.info-skill td.info-data').text pilot.skill container.find('tr.info-skill').show() container.find('tr.info-engagement td.info-data').text pilot.skill container.find('tr.info-engagement').show() container.find('tr.info-attack td.info-data').text(pilot.ship_override?.attack ? ship.attack) container.find('tr.info-attack').toggle(pilot.ship_override?.attack? or ship.attack?) container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf) container.find('tr.info-attack-fullfront').toggle(ship.attackf?) container.find('tr.info-attack-bullseye td.info-data').text(ship.attackbull) container.find('tr.info-attack-bullseye').toggle(ship.attackbull?) container.find('tr.info-attack-left td.info-data').text(ship.attackl) container.find('tr.info-attack-left').toggle(ship.attackl?) container.find('tr.info-attack-right td.info-data').text(ship.attackr) container.find('tr.info-attack-right').toggle(ship.attackr?) container.find('tr.info-attack-back td.info-data').text(ship.attackb?) container.find('tr.info-attack-back').toggle(ship.attackb?) container.find('tr.info-attack-turret td.info-data').text(ship.attackt?) container.find('tr.info-attack-turret').toggle(ship.attackt?) container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt) container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?) # for cls in container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList # container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc') container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-frontarc') container.find('tr.info-energy td.info-data').text(pilot.ship_override?.energy ? ship.energy) container.find('tr.info-energy').toggle(pilot.ship_override?.energy? or ship.energy?) container.find('tr.info-range').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-agility td.info-data').text(pilot.ship_override?.agility ? ship.agility) container.find('tr.info-agility').show() container.find('tr.info-hull td.info-data').text(pilot.ship_override?.hull ? ship.hull) container.find('tr.info-hull').show() container.find('tr.info-shields td.info-data').text(pilot.ship_override?.shields ? ship.shields) container.find('tr.info-shields').show() if effective_stats?.force? or data.force? container.find('tr.info-force td.info-data').html ((pilot.ship_override?.force ? pilot.force)+ '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').show() else container.find('tr.info-force').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').show() else container.find('tr.info-charge').hide() container.find('tr.info-actions td.info-data').html @formatActions(pilot.ship_override?.actions ? exportObj.ships[data.ship].actions, ", ", pilot.keyword ? []) container.find('tr.info-actions').show() container.find('tr.info-upgrades').show() container.find('tr.info-upgrades td.info-data').html(((if exportObj.upgrades[upgrade].display_name? then exportObj.upgrades[upgrade].display_name else upgrade) for upgrade in (data.upgrades ? [])).join(', ') or 'None') container.find('p.info-maneuvers').show() container.find('p.info-maneuvers').html(@getManeuverTableHTML(ship.maneuvers, ship.maneuvers)) when 'Addon' container.find('.info-type').text additional_opts.addon_type container.find('.info-sources.info-data').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') container.find('.info-sources').show() #logic to determine how many dots to use for uniqueness if data.unique? uniquedots = "&middot;&nbsp;" else if data.max_per_squad? count = 0 uniquedots = "" while (count < data.max_per_squad) uniquedots = uniquedots.concat("&middot;") ++count uniquedots = uniquedots.concat("&nbsp;") else uniquedots = "" if @collection?.counts? addon_count = @collection.counts?['upgrade']?[data.name] ? 0 container.find('.info-collection').text """You have #{addon_count} in your collection.""" container.find('.info-collection').show() else container.find('.info-collection').hide() container.find('.info-name').html """#{uniquedots}#{if data.display_name then data.display_name else data.name}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" if data.pointsarray? point_info = "<i><b>Point cost:</b> " + data.pointsarray + " when " if data.variableagility? and data.variableagility point_info += "agility is " + [0..data.pointsarray.length-1] else if data.variableinit? and data.variableinit point_info += "initiative is " + [0..data.pointsarray.length-1] else if data.variablebase? and data.variablebase point_info += " base size is small, medium, large or huge" point_info += "</i>" restriction_info = @restriction_text(data) + @upgrade_effect(data) if point_info? or (restriction_info != '') if point_info? and (restriction_info != '') point_info += "<br/>" container.find('p.info-restrictions').html (point_info ? '') + restriction_info container.find('p.info-restrictions').show() else container.find('p.info-restrictions').hide() container.find('p.info-text').html (data.text ? '') container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-engagement').hide() if data.energy? container.find('tr.info-energy td.info-data').text data.energy container.find('tr.info-energy').show() else container.find('tr.info-energy').hide() if data.attack? container.find('tr.info-attack td.info-data').text data.attack container.find('tr.info-attack').show() else container.find('tr.info-attack').hide() if data.attackt? container.find('tr.info-attack-turret td.info-data').text data.attackt container.find('tr.info-attack-turret').show() else container.find('tr.info-attack-turret').hide() if data.attackr? container.find('tr.info-attack-right td.info-data').text data.attackr container.find('tr.info-attack-right').show() else container.find('tr.info-attack-right').hide() if data.attackl? container.find('tr.info-attack-left td.info-data').text data.attackl container.find('tr.info-attack-left').show() else container.find('tr.info-attack-right').hide() if data.attackdt? container.find('tr.info-attack-doubleturret td.info-data').text data.attackdt container.find('tr.info-attack-doubleturret').show() else container.find('tr.info-attack-doubleturret').hide() if data.attackbull? container.find('tr.info-attack-bullseye td.info-data').text data.attackbull container.find('tr.info-attack-bullseye').show() else container.find('tr.info-attack-bullseye').hide() if data.attackf? container.find('tr.info-attack-fullfront td.info-data').text data.attackf container.find('tr.info-attack-fullfront').show() else container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-right').hide() container.find('tr.info-attack-left').hide() container.find('tr.info-attack-back').hide() if data.charge? recurringicon = '' if data.recurring? if data.recurring > 0 count = 0 while count < data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """#{data.charge}#{recurringicon}""" container.find('tr.info-charge td.info-data').html (chargeHTML) container.find('tr.info-charge').toggle(data.charge?) if data.range? container.find('tr.info-range td.info-data').text data.range container.find('tr.info-range').show() else container.find('tr.info-range').hide() if data.rangebonus? container.find('td.info-rangebonus').show() else container.find('td.info-rangebonus').hide() container.find('tr.info-force td.info-data').html (data.force + '<sup><i class="fas fa-caret-up"></i></sup>') container.find('tr.info-force').toggle(data.force?) container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() when 'Rules' container.find('.info-type').hide() container.find('.info-sources').hide() container.find('.info-collection').hide() container.find('.info-name').html data.name container.find('.info-name').show() container.find('p.info-restrictions').hide() container.find('p.info-text').html data.text container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() container.find('tr.info-energy').hide() container.find('tr.info-attack').hide() container.find('tr.info-attack-turret').hide() container.find('tr.info-attack-bullseye').hide() container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-back').hide() container.find('tr.info-attack-doubleturret').hide() container.find('tr.info-charge').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-range').hide() container.find('tr.info-force').hide() when 'MissingStuff' container.find('.info-type').text "List of Missing items" container.find('.info-sources').hide() container.find('.info-collection').hide() container.find('.info-name').html "Missing items" container.find('.info-name').show() missingStuffInfoText = "To field this squad you need the following additional items: <ul>" for item in data missingStuffInfoText += """<li><strong>#{(if item.display_name? then item.display_name else item.name)}</strong> (""" first = true for source in item.sources if not first missingStuffInfoText += ", " missingStuffInfoText += source first = false missingStuffInfoText += ")</li>" missingStuffInfoText +="</ul>" container.find('p.info-restrictions').hide() container.find('p.info-text').html missingStuffInfoText container.find('p.info-text').show() container.find('tr.info-ship').hide() container.find('tr.info-base').hide() container.find('tr.info-skill').hide() container.find('tr.info-agility').hide() container.find('tr.info-hull').hide() container.find('tr.info-shields').hide() container.find('tr.info-actions').hide() container.find('tr.info-upgrades').hide() container.find('p.info-maneuvers').hide() container.find('tr.info-energy').hide() container.find('tr.info-attack').hide() container.find('tr.info-attack-turret').hide() container.find('tr.info-attack-bullseye').hide() container.find('tr.info-attack-fullfront').hide() container.find('tr.info-attack-back').hide() container.find('tr.info-attack-doubleturret').hide() container.find('tr.info-charge').hide() container.find('td.info-rangebonus').hide() container.find('tr.info-range').hide() container.find('tr.info-force').hide() if container != @mobile_tooltip_modal container.show() @tooltip_currently_displaying = data # fix card viewer to view, if it is fully visible (it might not be e.g. on mobile devices. In that case keep it on its static position, so you can scroll to see it) if $(window).width() >= 768 well = container.find('.info-well') if $.isElementInView(well, true) well.css('position','fixed') else well.css('position','static') _randomizerLoopBody: (data) => if data.keep_running #console.log "Current points: #{@total_points} of #{data.max_points}, iteration=#{data.iterations} of #{data.max_iterations}, keep_running=#{data.keep_running}" if data.max_points - @total_points <= data.bid_goal and @total_points <= data.max_points # Hit bid range #console.log "Points reached exactly" data.keep_running = false else if @total_points < data.max_points #console.log "Need to add something" # Add something # Possible options: ship or empty addon slot unused_addons = [] for ship in @ships for upgrade in ship.upgrades unused_addons.push upgrade unless upgrade.data? or (upgrade.occupied_by? and upgrade.occupied_by != null) # 0 is ship, otherwise addon idx = $.randomInt(data.ships_or_upgrades + unused_addons.length) if idx < data.ships_or_upgrades or unused_addons.length == 0 # Add random ship #console.log "Add ship" available_ships = @getAvailableShipsMatchingAndCheapEnough(data.max_points - @total_points, '', false, data.collection_only) if available_ships.length == 0 if unused_addons.length > 0 idx = $.randomInt(unused_addons.length) + data.ships_or_upgrades else available_ships = @getAvailableShipsMatching('', false, data.collection_only) if (available_ships.length > 0) and ((@ships.length < data.ship_limit) or (data.ship_limit == 0)) ship_type = available_ships[$.randomInt available_ships.length].name available_pilots = @getAvailablePilotsForShipIncluding(ship_type) if available_pilots.length == 0 # edge case: It might have been a ship selected, that has only unique pilots - which all have been already selected return pilot = available_pilots[$.randomInt available_pilots.length] if not pilot.disabled and (if @isQuickbuild then exportObj.pilots[exportObj.quickbuildsById[pilot.id].pilot] else exportObj.pilotsById[pilot.id]).sources.intersects(data.allowed_sources) and ((not data.collection_only) or @collection.checkShelf('pilot', (if @isQuickbuild then exportObj.quickbuildsById[pilot.id] else pilot.name))) new_ship = @addShip() new_ship.setPilotById pilot.id if idx >= data.ships_or_upgrades and unused_addons.length != 0 # Add upgrade #console.log "Add addon" addon = unused_addons[idx - data.ships_or_upgrades] switch addon.type when 'Upgrade' available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship, addon,'', @dfl_filter_func, sorted = false) when (exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources) and ((not data.collection_only) or @collection.checkShelf('upgrade', upgrade.name)))) upgrade = if available_upgrades.length > 0 then available_upgrades[$.randomInt available_upgrades.length] else undefined if upgrade and not upgrade.disabled addon.setById upgrade.id else throw new Error("Invalid addon type #{addon.type}") else #console.log "Need to remove something" # Remove something removable_things = [] for ship in @ships for _ in [0...(11-data.ships_or_upgrades)] removable_things.push ship for upgrade in ship.upgrades removable_things.push upgrade if upgrade.data? if removable_things.length > 0 thing_to_remove = removable_things[$.randomInt removable_things.length] #console.log "Removing #{thing_to_remove}" if thing_to_remove instanceof Ship @removeShip thing_to_remove else if thing_to_remove instanceof GenericAddon thing_to_remove.setData null else throw new Error("Unknown thing to remove #{thing_to_remove}") # continue the "loop" window.setTimeout @_makeRandomizerLoopFunc(data), 0 else #console.log "Clearing timer #{data.timer}, iterations=#{data.iterations}, keep_running=#{data.keep_running}" # we have to stop randomizing, but should do a final check on our point costs. while @total_points > data.max_points removable_things = [] for ship in @ships # removable_things.push ship for upgrade in ship.upgrades removable_things.push upgrade if upgrade.data? if removable_things.length == 0 for ship in @ships removable_things.push ship if removable_things.length > 0 thing_to_remove = removable_things[$.randomInt removable_things.length] #console.log "Removing #{thing_to_remove}" if thing_to_remove instanceof Ship @removeShip thing_to_remove else if thing_to_remove instanceof GenericAddon thing_to_remove.setData null else throw new Error("Unknown thing to remove #{thing_to_remove}") if data.fill_zero_pts for ship in @ships for addon in ship.upgrades continue unless not (addon.data? or (addon.occupied_by? and addon.occupied_by != null)) available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship, addon,'', @dfl_filter_func, sorted = false) when (exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources) and (upgrade.points < 1) and ((not data.collection_only) or @collection.checkShelf('upgrade', upgrade.name)))) upgrade = if available_upgrades.length > 0 then available_upgrades[$.randomInt available_upgrades.length] else undefined if upgrade and not upgrade.disabled addon.setById upgrade.id window.clearTimeout data.timer # Update all selectors for ship in @ships ship.updateSelections() @suppress_automatic_new_ship = false @addShip() _makeRandomizerLoopFunc: (data) => () => @_randomizerLoopBody(data) randomSquad: (max_points=200, allowed_sources=null, timeout_ms=1000, bid_goal=5, ship_limit=0, ships_or_upgrades=3, collection_only=true, fill_zero_pts=false) -> @backend_status.fadeOut 'slow' @suppress_automatic_new_ship = true if allowed_sources.length < 1 allowed_sources = null # Clear all existing ships while @ships.length > 0 @removeShip @ships[0] throw new Error("Ships not emptied") if @ships.length > 0 data = max_points: max_points bid_goal: bid_goal ship_limit: ship_limit ships_or_upgrades: ships_or_upgrades keep_running: true allowed_sources: allowed_sources ? exportObj.expansions collection_only: @collection? and (@collection.checks.collectioncheck == "true") and collection_only fill_zero_pts: fill_zero_pts stopHandler = () => #console.log "*** TIMEOUT *** TIMEOUT *** TIMEOUT ***" data.keep_running = false data.timer = window.setTimeout stopHandler , timeout_ms #console.log "Timer set for #{timeout_ms}ms, timer is #{data.timer}" window.setTimeout @_makeRandomizerLoopFunc(data), 0 @resetCurrentSquad() @current_squad.name = 'PI:NAME:<NAME>END_PI' @container.trigger 'xwing-backend:squadNameChanged' setBackend: (backend) -> @backend = backend if @waiting_for_backend? for meth in @waiting_for_backend meth() upgrade_effect: (card) -> removestext = text = comma = '' if card.modifier_func statchange = attack: 0 attackf: 0 attackbull: 0 attackb: 0 attackt: 0 attackl: 0 attackr: 0 attackdt: 0 energy: 0 agility: 0 hull: 0 shields: 0 force: 0 actions: [] maneuvers: [0, 0] card.modifier_func(statchange) if statchange.attack != 0 text += comma + "%FRONTARC% (#{statchange.attack})" comma = ', ' if statchange.attackf != 0 text += comma + "%FULLFRONTARC% (#{statchange.attackf})" comma = ', ' if statchange.attackbull != 0 text += comma + "%BULLSEYEARC% (#{statchange.attackbull})" comma = ', ' if statchange.attackb != 0 text += comma + "%REARARC% (#{statchange.attackb})" comma = ', ' if statchange.attackt != 0 text += comma + "%SINGLETURRETARC% (#{statchange.attackt})" comma = ', ' if statchange.attackl != 0 text += comma + "%LEFTARC% (#{statchange.attackl})" comma = ', ' if statchange.attackr != 0 text += comma + "%RIGHTARC% (#{statchange.attackr})" comma = ', ' if statchange.attackdt != 0 text += comma + "%DOUBLETURRETARC% (#{statchange.attackdt})" comma = ', ' if statchange.energy != 0 text += comma + "%ENERGY% (#{statchange.energy})" comma = ', ' if statchange.agility != 0 text += comma + "%AGILITY% (#{statchange.agility})" comma = ', ' if statchange.hull != 0 text += comma + "%HULL% (#{statchange.hull})" comma = ', ' if statchange.shields != 0 text += comma + "%SHIELD% (#{statchange.shields})" comma = ', ' if statchange.actions.length > 0 text += comma + @formatActions(statchange.actions, ", ") comma = ', ' if card.confersAddons for addonname in card.confersAddons text += comma + "%#{addonname.slot.toUpperCase().replace(/[^a-z0-9]/gi, '')}%" comma = ', ' if card.unequips_upgrades comma = '' for slot in card.unequips_upgrades removestext += comma + "%#{slot.toUpperCase().replace(/[^a-z0-9]/gi, '')}%" comma = ', ' if text != '' data = text: "</br><b>Adds:</b> #{text}" if removestext != '' data.text += "</br><b>Removes:</b> #{removestext}" return exportObj.fixIcons(data) else return '' restriction_text: (card) -> uniquetext = comma = othertext = text = '' if card.restrictions for r in card.restrictions if r[0] == "orUnique" uniquetext = exportObj.translate(@language, 'restrictions', " or Squad Including") + " #{r[1]}" continue switch r[0] when "Base" text += comma + "#{r[1]} " + exportObj.translate(@language, 'restrictions', "Ship") when "Action" array = [r[1]] text += comma + @formatActions(array,"", []) when "Equipped" text += comma + "%#{r[1].toUpperCase().replace(/[^a-z0-9]/gi, '')}% Equipped" when "Slot" text += comma + exportObj.translate(@language, 'restrictions', "Extra") + " %#{r[1].toUpperCase().replace(/[^a-z0-9]/gi, '')}%" when "Keyword" text += comma + exportObj.translate(@language, 'restrictions', "#{r[1]}") when "AttackArc" text += comma + "%REARARC%" when "ShieldsGreaterThan" text += comma + "%SHIELD% > #{r[1]}" when "EnergyGreatterThan" text += comma + "%ENERGY% > #{r[1]}" when "InitiativeGreaterThan" text += comma + exportObj.translate(@language, 'restrictions', "Initiative") + " > #{r[1]}" when "InitiativeLessThan" text += comma + exportObj.translate(@language, 'restrictions', "Initiative")+ " < #{r[1]}" when "AgilityEquals" text += comma + exportObj.translate(@language, 'restrictions', "Agility") + " = #{r[1]}" when "isUnique" if r[1] == true text += comma + exportObj.translate(@language, 'restrictions', "Limited") else text += comma + exportObj.translate(@language, 'restrictions', "Non-Limited") when "Format" text += comma + exportObj.translate(@language, 'restrictions', "#{r[1]} Ship") when "Faction" othertext += comma + exportObj.translate(@language, 'faction', "#{r[1]}") comma = ', ' if not card.skill if othertext == '' if card.faction if card.faction instanceof Array for factionitem in card.faction othertext += comma + exportObj.translate(@language, 'faction', "#{factionitem}") comma = ' or ' else othertext += comma + exportObj.translate(@language, 'faction', "#{card.faction}") comma = ', ' if card.ship if card.ship instanceof Array for shipname in card.ship othertext += comma + shipname comma = ' or ' else othertext += comma + card.ship comma = ', ' if card.solitary othertext += comma + exportObj.translate(@language, 'faction', "Solitary") comma = ', ' if card.standardized othertext += comma + exportObj.translate(@language, 'faction', "Standardized") comma = ', ' text += othertext + uniquetext if text != '' data = text: "<i><b>" + exportObj.translate(@language, 'restrictions', "Restrictions") + ":</b> " + text + "</i>" return exportObj.fixIcons(data) else return '' describeSquad: -> if @getNotes().trim() == '' then ((ship.pilot.name for ship in @ships when ship.pilot?).join ', ') else @getNotes() listCards: -> card_obj = {} for ship in @ships if ship.pilot? card_obj[ship.pilot.name] = null for upgrade in ship.upgrades card_obj[upgrade.data.name] = null if upgrade.data? return Object.keys(card_obj).sort() getNotes: -> @notes.val() getTag: -> @tag.val() getObstacles: -> @current_obstacles isSquadPossibleWithCollection: -> # If the collection is uninitialized or empty, don't actually check it. if Object.keys(@collection?.expansions ? {}).length == 0 # console.log "collection not ready or is empty" return [true, []] else if @collection?.checks.collectioncheck != "true" # console.log "collection check not enabled" return [true, []] @collection.reset() validity = true missingStuff = [] for ship in @ships if ship.pilot? # Try to get both the physical model and the pilot card. ship_is_available = @collection.use('ship', ship.pilot.ship) pilot_is_available = @collection.use('pilot', ship.pilot.name) # console.log "#{@faction}: Ship #{ship.pilot.ship} available: #{ship_is_available}" # console.log "#{@faction}: Pilot #{ship.pilot.name} available: #{pilot_is_available}" validity = false unless ship_is_available and pilot_is_available missingStuff.push ship.data unless ship_is_available missingStuff.push ship.pilot unless pilot_is_available for upgrade in ship.upgrades if upgrade.data? upgrade_is_available = @collection.use('upgrade', upgrade.data.name) # console.log "#{@faction}: Upgrade #{upgrade.data.name} available: #{upgrade_is_available}" validity = false unless upgrade_is_available missingStuff.push upgrade.data unless upgrade_is_available [validity, missingStuff] checkCollection: -> # console.log "#{@faction}: Checking validity of squad against collection..." if @collection? [squadPossible, missingStuff] = @isSquadPossibleWithCollection() @collection_invalid_container.toggleClass 'd-none', squadPossible @collection_invalid_container.on 'mouseover', (e) => @showTooltip 'MissingStuff', missingStuff toXWS: -> # Often you will want JSON.stringify(builder.toXWS()) xws = description: @getNotes() faction: exportObj.toXWSFaction[@faction] name: @current_squad.name pilots: [] points: @total_points vendor: yasb: builder: 'YASB 2.0' builder_url: window.location.href.split('?')[0] link: @getPermaLink() version: '2.0.0' for ship in @ships if ship.pilot? xws.pilots.push ship.toXWS() # Associate multisection ships # This maps id to list of pilots it comprises multisection_id_to_pilots = {} last_id = 0 unmatched = (pilot for pilot in xws.pilots when pilot.multisection?) for _ in [0...(unmatched.length ** 2)] break if unmatched.length == 0 # console.log "Top of loop, unmatched: #{m.name for m in unmatched}" unmatched_pilot = unmatched.shift() unmatched_pilot.multisection_id ?= last_id++ multisection_id_to_pilots[unmatched_pilot.multisection_id] ?= [unmatched_pilot] break if unmatched.length == 0 # console.log "Finding matches for #{unmatched_pilot.name} (assigned id=#{unmatched_pilot.multisection_id})" matches = [] for candidate in unmatched # console.log "-> examine #{candidate.name}" if unmatched_pilot.name in candidate.multisection matches.push candidate unmatched_pilot.multisection.removeItem candidate.name candidate.multisection.removeItem unmatched_pilot.name candidate.multisection_id = unmatched_pilot.multisection_id # console.log "-> MATCH FOUND #{candidate.name}, assigned id=#{candidate.multisection_id}" multisection_id_to_pilots[candidate.multisection_id].push candidate if unmatched_pilot.multisection.length == 0 # console.log "-> No more sections to match for #{unmatched_pilot.name}" break for match in matches if match.multisection.length == 0 # console.log "Dequeue #{match.name} since it has no more sections to match" unmatched.removeItem match for pilot in xws.pilots delete pilot.multisection if pilot.multisection? obstacles = @getObstacles() if obstacles? and obstacles.length > 0 xws.obstacles = obstacles xws toMinimalXWS: -> # Just what's necessary xws = @toXWS() # Keep mandatory stuff only for own k, v of xws delete xws[k] unless k in ['faction', 'pilots', 'version'] for own k, v of xws.pilots delete xws[k] unless k in ['id', 'upgrades', 'multisection_id'] xws loadFromXWS: (xws, cb) -> success = null error = null if xws.version? version_list = (parseInt x for x in xws.version.split('.')) else version_list = [0,2] # Version tag is optional, so let's just assume it is some 2.0 xws if no version is given switch # Not doing backward compatibility pre-1.x when version_list > [0, 1] xws_faction = exportObj.fromXWSFaction[xws.faction] if @faction != xws_faction throw new Error("Attempted to load XWS for #{xws.faction} but builder is #{@faction}") if xws.name? @current_squad.name = xws.name if xws.description? @notes.val xws.description if xws.obstacles? @current_squad.additional_data.obstacles = xws.obstacles @suppress_automatic_new_ship = true @removeAllShips() success = true error = "" serialized_squad = "v8ZsZ200Z" # serialization version 7, standard squad, 200 points # serialization schema SHIPID:UPGRADEID,UPGRADEID,...,UPGRADEID:;SHIPID:UPGRADEID,... for pilot in xws.pilots new_ship = @addShip() # we add some backward compatibility here, to allow imports from Launch Bay Next Squad Builder # According to xws-spec, for 2nd edition we use id instead of name # however, we will accept a name instead of an id as well. if pilot.id pilotxws = pilot.id else if pilot.name pilotxws = pilot.name else success = false error = "Pilot without identifier" break # add pilot id if exportObj.pilotsByFactionXWS[xws_faction][pilotxws]? serialized_squad += exportObj.pilotsByFactionXWS[xws_faction][pilotxws][0].id else if exportObj.pilotsByUniqueName[pilotxws] and exportObj.pilotsByUniqueName[pilotxws].length == 1 serialized_squad += exportObj.pilotsByUniqueName[pilotxws][0].id else for key, possible_pilots of exportObj.pilotsByUniqueName for possible_pilot in possible_pilots if (possible_pilot.xws and possible_pilot.xws == pilotxws) or (not possible_pilot.xws and key == pilotxws) serialized_squad += possible_pilot.id break serialized_squad += "X" # add upgrade ids # Turn all the upgrades into a flat list so we can keep trying to add them addons = [] for upgrade_type, upgrade_canonicals of pilot.upgrades ? {} for upgrade_canonical in upgrade_canonicals # console.log upgrade_type, upgrade_canonical slot = null slot = exportObj.fromXWSUpgrade[upgrade_type] ? upgrade_type.capitalize() upgrade = exportObj.upgradesBySlotXWSName[slot][upgrade_canonical] ?= exportObj.upgradesBySlotCanonicalName[slot][upgrade_canonical] if not upgrade? console.log("Failed to load xws upgrade: " + upgrade_canonical) error += "Skipped upgrade " + upgrade_canonical success = false continue serialized_squad += upgrade.id serialized_squad += "W" serialized_squad += "XY" @loadFromSerialized(serialized_squad) @current_squad.dirty = true @container.trigger 'xwing-backend:squadNameChanged' @container.trigger 'xwing-backend:squadDirtinessChanged' cb success: success error: error class Ship constructor: (args) -> # args @builder = args.builder @container = args.container # internal state @pilot = null @data = null # ship data @quickbuildId = -1 @linkedShip = null # some quickbuilds contain two ships, this variable may reference a Ship beeing part of the same quickbuild card @primary = true # only the primary ship of a linked ship pair will contribute points and serialization id @upgrades = [] @wingmates = [] # stores wingmates (quickbuild stuff only) @destroystate = null @setupUI() destroy: (cb) -> @resetPilot() @resetAddons() @teardownUI() idx = @builder.ships.indexOf this if idx < 0 throw new Error("Ship not registered with builder") @builder.ships.splice idx, 1 if @wingmates.length > 0 @setWingmates(0) else if @linkedShip != null @linkedShip.linkedShip = null if @linkedShip.wingmates?.length > 0 @linkedShip.removeFromWing(this) else await @builder.removeShip @linkedShip, defer() cb() copyFrom: (other) -> throw new Error("Cannot copy from self") if other is this #console.log "Attempt to copy #{other?.pilot?.name}" return unless other.pilot? and other.data? #console.log "Setting pilot to ID=#{other.pilot.id}" if @builder.isQuickbuild if not (other.pilot.unique or (other.pilot.max_per_squad? and @builder.countPilots(other.pilot.canonical_name) >= other.pilot.max_per_squad)) # check if any upgrades are unique. In that case the whole ship may not be copied no_uniques_involved = true for upgrade in other.upgrades if (upgrade.data?.unique? and upgrade.data.unique) or (upgrade.data?.max_per_squad? and @builder.countUpgrades(upgrade.data.canonical_name) >= upgrade.data.max_per_squad) or upgrade.data?.solitary? no_uniques_involved = false # select cheapest generic like above available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled) if available_pilots.length > 0 @setPilotById available_pilots[0].id, true break else return if no_uniques_involved @setPilotById other.quickbuildId else if other.pilot.unique or (other.pilot.max_per_squad? and @builder.countPilots(other.pilot.canonical_name) >= other.pilot.max_per_squad) # Look for cheapest generic or available unique, otherwise do nothing available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled) if available_pilots.length > 0 @setPilotById available_pilots[0].id, true else return else @setPilotById other.pilot.id, true # Can't just copy upgrades since slots may be different other_upgrades = {} for upgrade in other.upgrades if upgrade?.data? and not upgrade.data.unique and ((not upgrade.data.max_per_squad?) or @builder.countUpgrades(upgrade.data.canonical_name) < upgrade.data.max_per_squad) other_upgrades[upgrade.slot] ?= [] other_upgrades[upgrade.slot].push upgrade delayed_upgrades = {} for upgrade in @upgrades other_upgrade = (other_upgrades[upgrade.slot] ? []).shift() if other_upgrade? upgrade.setById other_upgrade.data.id if not upgrades.lastSetValid delayed_upgrades[other_upgrade.data.id] = upgrade for id, upgrade of delayed_upgrades upgrade.setById id @addStandardizedUpgrades() @updateSelections() @builder.container.trigger 'xwing:pointsUpdated' @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' setShipType: (ship_type) -> @pilot_selector.data('select2').container.show() if ship_type != @pilot?.ship if not @builder.isQuickbuild # Ship changed; select first non-unique pilot = (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not exportObj.pilotsById[result.id].unique)[0] if pilot # if there is a non-unique, use this one @setPilot pilot else # otherwise just set it to the first available pilot @setPilot (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when ((not exportObj.pilotsById[result.id].restriction_func? or exportObj.pilotsById[result.id].restriction_func(@)) and not (exportObj.pilotsById[result.id] in @builder.uniques_in_use.Pilot)))[0] else # get the first available pilot quickbuild_id = (result.id for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not result.disabled)[0] @setPilotById quickbuild_id @checkPilotSelectorQueryModal() # Clear ship background class for cls in @row.attr('class').split(/\s+/) if cls.indexOf('ship-') == 0 @row.removeClass cls # Show delete button @remove_button.fadeIn 'fast' @copy_button.fadeIn 'fast' @points_destroyed_button.fadeIn 'fast' # Ship background @row.addClass "ship-#{ship_type.toLowerCase().replace(/[^a-z0-9]/gi, '')}" @builder.container.trigger 'xwing:shipUpdated' setPilotById: (id, noautoequip = false) -> #sets pilot of this ship according to given id. Id might be pilotId or quickbuildId depending on mode. if not @builder.isQuickbuild @setPilot exportObj.pilotsById[parseInt id], noautoequip else if id != @quickbuildId @wingmate_selector.parent().hide() if @wingmates? and @wingmates.length > 0 # remove any wingmates, as the wing leader was just removed from the list @setWingmates(0) @linkedShip = null @quickbuildId = id @builder.current_squad.dirty = true @resetPilot() @resetAddons() if id? and id > -1 quickbuild = exportObj.quickbuildsById[parseInt id] new_pilot = exportObj.pilots[quickbuild.pilot] @data = exportObj.ships[quickbuild.ship] @builder.isUpdatingPoints = true # prevents unneccesary validations while still adding stuff if new_pilot?.unique? await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ] @pilot = new_pilot @setupAddons() if @pilot? @copy_button.show() @setShipType @pilot.ship # if this card contains more than one ship, make sure the other one is added as well if quickbuild.wingmate? && not @linkedShip? # try to join wingleader, if we have not been created by him for ship in @builder.ships if ship.quickbuildId == quickbuild.linkedId # found our leader. join him. ship.joinWing(this) @linkedShip = ship @primary = false @builder.isUpdatingPoints = false @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' return # we are done. if @linkedShip # we are already linked to some other ship if quickbuild.linkedId? # we will stay linked to another ship, so just set the linked one to an new pilot es well @linkedShip.setPilotById quickbuild.linkedId @linkedShip.primary = false unless quickbuild.wingmate? else # take care of associated ship if @linkedShip.wingmates?.length > 0 # we are no longer part of a wing @linkedShip.removeFromWing(this) else # we are no longer part of a linked pair, so the linked ship should be removed @linkedShip.linkedShip = null await @builder.removeShip @linkedShip, defer() @linkedShip = null else if quickbuild.linkedId? # we nare not already linked to another ship, but need one. Let's set one up @linkedShip = @builder.ships.slice(-1)[0] # during squad building there is an empty ship at the bottom, use that one and add a new empty one. # during squad loading there is no empty ship at the bottom, so we just create a new one and use it if @linkedShip.data != null @linkedShip = @builder.addShip() else @builder.addShip() @linkedShip.linkedShip = this @linkedShip.setPilotById quickbuild.linkedId # for pairs the first selected ship is master, so as we have been created first, we set the other ship to false # for wings the wingleader is always master, so we don't set the other ship to false, if we are just a wingmate @linkedShip.primary = false unless quickbuild.wingmate? @primary = !quickbuild.wingmate? if quickbuild?.wingleader? @wingmate_selector.parent().show() @wingmate_selector.val quickbuild.wingmates[0] @wingmate_selector.attr "min", quickbuild.wingmates[0] @wingmate_selector.attr "max", quickbuild.wingmates[quickbuild.wingmates.length - 1] @setWingmates quickbuild.wingmates[0] @builder.isUpdatingPoints = false @builder.container.trigger 'xwing:pointsUpdated' else @copy_button.hide() @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' addStandardizedUpgrades: -> idx = @builder.standard_list['Ship'].indexOf @data.name if idx > -1 for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, @builder.standard_list['Upgrade'][idx].slot) upgrade.setData @builder.standard_list['Upgrade'][idx] break setPilot: (new_pilot, noautoequip = false) -> # don't call this method directly, unless you know what you do. Use setPilotById for proper quickbuild handling if new_pilot != @pilot @builder.current_squad.dirty = true same_ship = @pilot? and new_pilot?.ship == @pilot.ship old_upgrades = {} if same_ship # track addons and try to reassign them for upgrade in @upgrades if upgrade?.data? old_upgrades[upgrade.slot] ?= [] old_upgrades[upgrade.slot].push upgrade @resetPilot() @resetAddons() if new_pilot? @data = exportObj.ships[new_pilot?.ship] if new_pilot?.unique? await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ] @pilot = new_pilot @setupAddons() if @pilot? @copy_button.show() @setShipType @pilot.ship @addStandardizedUpgrades() if (@pilot.autoequip? or (exportObj.ships[@pilot.ship].autoequip? and not same_ship)) and not noautoequip autoequip = (@pilot.autoequip ? []).concat(exportObj.ships[@pilot.ship].autoequip ? []) for upgrade_name in autoequip auto_equip_upgrade = exportObj.upgrades[upgrade_name] for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, auto_equip_upgrade.slot) upgrade.setData auto_equip_upgrade if same_ship delayed_upgrades = {} for upgrade in @upgrades old_upgrade = (old_upgrades[upgrade.slot] ? []).shift() if old_upgrade? upgrade.setById old_upgrade.data.id if not upgrade.lastSetValid delayed_upgrades[old_upgrade.data.id] = upgrade for id, upgrade of delayed_upgrades upgrade.setById id else @copy_button.hide() @builder.container.trigger 'xwing:pointsUpdated' @builder.container.trigger 'xwing-backend:squadDirtinessChanged' resetPilot: -> if @pilot?.unique? await @builder.container.trigger 'xwing:releaseUnique', [ @pilot, 'Pilot', defer() ] @pilot = null setupAddons: -> if not @builder.isQuickbuild # Upgrades from pilot for slot in @pilot.slots ? [] @upgrades.push new exportObj.Upgrade ship: this container: @addon_container slot: slot else # Upgrades from quickbuild for upgrade_name in exportObj.quickbuildsById[@quickbuildId].upgrades ? [] upgrade_data = exportObj.upgrades[upgrade_name] if not upgrade_data? console.log("Unknown Upgrade: " + upgrade_name) continue upgrade = new exportObj.QuickbuildUpgrade ship: this container: @addon_container slot: upgrade_data.slot upgrade: upgrade_data upgrade.setData upgrade_data @upgrades.push upgrade resetAddons: -> await for upgrade in @upgrades upgrade.destroy defer() if upgrade? @upgrades = [] getPoints: -> if not @builder.isQuickbuild points = @pilot?.points ? 0 for upgrade in @upgrades points += upgrade.getPoints() @points_container.find('span').text points if points > 0 @points_container.fadeTo 'fast', 1 else @points_container.fadeTo 0, 0 points else quickbuild = exportObj.quickbuildsById[@quickbuildId] threat = if @primary then quickbuild?.threat ? 0 else 0 if quickbuild?.wingleader? threat = quickbuild.threat[quickbuild.wingmates.indexOf(@wingmates.length)] @points_container.find('span').text threat if threat > 0 @points_container.fadeTo 'fast', 1 else @points_container.fadeTo 0, 0 threat setWingmates: (wingmates) -> # creates/destroys wingmates to match number given as argument # todo: Check if number is valid for this quickbuild wing? if @wingmates?.length == wingmates # nothing to do, we already have correct number of wingmates. return if !@wingmates? || @wingmates.length == 0 # if no wingmates are set yet, use the linked buddy @wingmates = [@linkedShip] quickbuild = exportObj.quickbuildsById[@quickbuildId] while @wingmates.length < wingmates # create more wingmates newMate = @builder.ships.slice(-1)[0] # during squad building there is an empty ship at the bottom, use that one and add a new empty one. # during squad loading there is no empty ship at the bottom, so we just create a new one and use it if newMate.data != null newMate = @builder.addShip() else @builder.addShip() newMate.linkedShip = this # link new mate to us @wingmates.push(newMate) newMate.setPilotById quickbuild.linkedId # for pairs the first selected ship is master, so as we have been created first, we set the other ship to false # for wings the wingleader is always master, so we don't set the other ship to false, if we are just a wingmate newMate.primary = false @primary = true # he should not try to steal our primary position, as he is aware of beeing not squad leader, but in case he's not just set it. while @wingmates.length > wingmates # destroy wingmates dyingMate = @wingmates.pop() dyingMate.linkedShip = null # prevent the mate from killing us await @builder.removeShip dyingMate, defer() @wingmate_selector.val wingmates removeFromWing: (ship) -> # remove requested ship from wing @wingmates.removeItem(ship) # check if the wing is still valid, otherwise destroy it. quickbuild = exportObj.quickbuildsById[@quickbuildId] if !(@wingmates.length in quickbuild.wingmates) @destroy $.noop @wingmate_selector.val @wingmates.length joinWing: (ship) -> # remove requested ship from wing @wingmates.push(ship) # check if the wing is still valid, otherwise destroy the added ship quickbuild = exportObj.quickbuildsById[@quickbuildId] if !(@wingmates.length in quickbuild.wingmates) ship.destroy $.noop @removeFromWing(ship) @wingmate_selector.val @wingmates.length updateSelections: -> if @pilot? @ship_selector.select2 'data', id: @pilot.ship text: if exportObj.ships[@pilot.ship].display_name then exportObj.ships[@pilot.ship].display_name else @pilot.ship xws: exportObj.ships[@pilot.ship].xws icon: if exportObj.ships[@pilot.ship].icon then exportObj.ships[@pilot.ship].icon else exportObj.ships[@pilot.ship].xws @pilot_selector.select2 'data', id: @pilot.id text: "#{if exportObj.settings?.initiative_prefix? and exportObj.settings.initiative_prefix then @pilot.skill + ' - ' else ''}#{if @pilot.display_name then @pilot.display_name else @pilot.name}#{if @quickbuildId != -1 then exportObj.quickbuildsById[@quickbuildId].suffix else ""} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})" @pilot_selector.data('select2').container.show() for upgrade in @upgrades points = upgrade.getPoints() upgrade.updateSelection points else @pilot_selector.select2 'data', null #@pilot_selector.data('select2').container.toggle(@ship_selector.val() != '') checkPilotSelectorQueryModal: -> if $(window).width() >= 768 @pilot_query_modal.hide() else if @pilot then @pilot_query_modal.show() setupUI: -> @row = $ document.createElement 'DIV' @row.addClass 'row ship mb-5 mb-sm-0' @row.insertBefore @builder.notes_container if @pilot? shipicon = if exportObj.ships[@pilot.ship].icon then exportObj.ships[@pilot.ship].icon else exportObj.ships[@pilot.ship].xws @row.append $.trim ''' <div class="col-md-3"> <div class="form-group d-flex"> <input class="ship-selector-container" type="hidden"></input> <div class="input-group-append"> <button class="btn btn-secondary d-block d-md-none ship-query-modal"><i class="fas fa-question"></i></button> </div> <br /> </div> <div class="form-group d-flex"> <input type="hidden" class="pilot-selector-container"></input> <div class="input-group-append"> <button class="btn btn-secondary pilot-query-modal"><i class="fas fa-question"></i></button> <br /> </div> </div> <label class="wingmate-label"> Wingmates: <input type="number" class="wingmate-selector"></input> </label> </div> <div class="col-md-1 points-display-container"> <span></span> </div> <div class="col-md-6 addon-container"> </div> <div class="col-md-2 button-container"> <button class="btn btn-danger remove-pilot side-button"><span class="d-none d-sm-block" data-toggle="tooltip" title="Remove Pilot"><i class="fa fa-times"></i></span><span class="d-block d-sm-none"> Remove Pilot</span></button> <button class="btn btn-light copy-pilot side-button"><span class="d-none d-sm-block" data-toggle="tooltip" title="Clone Pilot"><i class="far fa-copy"></i></span><span class="d-block d-sm-none"> Clone Pilot</span></button>&nbsp;&nbsp;&nbsp; <button class="btn btn-light points-destroyed side-button" points-state"><span class="destroyed-type" title="Points Destroyed"><i class="xwing-miniatures-font xwing-miniatures-font-title"></i></span></button> </div> ''' @row.find('.button-container span').tooltip() @ship_selector = $ @row.find('input.ship-selector-container') @pilot_selector = $ @row.find('input.pilot-selector-container') @wingmate_selector = $ @row.find('input.wingmate-selector') @ship_query_modal = $ @row.find('button.ship-query-modal') @pilot_query_modal = $ @row.find('button.pilot-query-modal') @ship_query_modal.click (e) => if @pilot @builder.showTooltip 'Ship', exportObj.ships[@pilot.ship], null, @builder.mobile_tooltip_modal, true @builder.mobile_tooltip_modal.modal 'show' @pilot_query_modal.click (e) => if @pilot @builder.showTooltip 'Pilot', @pilot, (@ if @pilot), @builder.mobile_tooltip_modal, true @builder.mobile_tooltip_modal.modal 'show' shipResultFormatter = (object, container, query) -> return """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.icon}"></i> #{object.text}""" shipSelectionFormatter = (object, container) -> return """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.icon}"></i> #{object.text}""" @ship_selector.select2 width: '100%' placeholder: exportObj.translate @builder.language, 'ui', 'shipSelectorPlaceholder' query: (query) => data = {results: []} data.results = @builder.getAvailableShipsMatching(query.term) query.callback(data) minimumResultsForSearch: if $.isMobile() then -1 else 0 formatResultCssClass: (obj) => if @builder.collection? and (@builder.collection.checks.collectioncheck == "true") not_in_collection = false if @pilot? and obj.id == exportObj.ships[@pilot.ship].id # Currently selected ship; mark as not in collection if it's neither # on the shelf nor on the table unless (@builder.collection.checkShelf('ship', obj.name) or @builder.collection.checkTable('pilot', obj.name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @builder.collection.checkShelf('ship', obj.name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' formatResult: shipResultFormatter formatSelection: shipResultFormatter @ship_selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @ship_selector.on 'change', (e) => @setShipType @ship_selector.val() @ship_selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' @builder.showTooltip 'Ship', exportObj.ships[select2_data.id] if select2_data?.id? @ship_selector.data('select2').container.on 'mouseover', (e) => @builder.showTooltip 'Ship', exportObj.ships[@pilot.ship] if @pilot @pilot_selector.select2 width: '100%' placeholder: exportObj.translate @builder.language, 'ui', 'pilotSelectorPlaceholder' query: (query) => data = {results: []} data.results = @builder.getAvailablePilotsForShipIncluding(@ship_selector.val(), (if not @builder.isQuickbuild then @pilot else @quickbuildId), query.term, true, @) query.callback(data) minimumResultsForSearch: if $.isMobile() then -1 else 0 formatResultCssClass: (obj) => if @builder.collection? and (@builder.collection.checks.collectioncheck == "true") not_in_collection = false name = "" if @builder.isQuickbuild name = exportObj.quickbuildsById[obj.id]?.pilot ? "unknown pilot" else name = obj.name if obj.id == @pilot?.id # Currently selected pilot; mark as not in collection if it's neither # on the shelf nor on the table unless (@builder.collection.checkShelf('pilot', name) or @builder.collection.checkTable('pilot', name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @builder.collection.checkShelf('pilot', name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' @pilot_selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @pilot_selector.on 'change', (e) => @setPilotById @pilot_selector.select2('val') @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' @builder.backend_status.fadeOut 'slow' @pilot_selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' if @builder.isQuickbuild @builder.showTooltip 'Quickbuild', exportObj.quickbuildsById[select2_data.id], {ship: @data?.name} if select2_data?.id? else @builder.showTooltip 'Pilot', exportObj.pilotsById[select2_data.id] if select2_data?.id? @pilot_selector.data('select2').container.on 'mouseover', (e) => @builder.showTooltip 'Pilot', @pilot, @ if @pilot @pilot_selector.data('select2').container.hide() if @builder.isQuickbuild @wingmate_selector.on 'change', (e) => @setWingmates parseInt @wingmate_selector.val() @builder.current_squad.dirty = true @builder.container.trigger 'xwing-backend:squadDirtinessChanged' @builder.backend_status.fadeOut 'slow' @wingmate_selector.on 'mousemove-filtered', (e) => return # TODO: show tooltip of wingmate # select2_data = $(e.target).closest('.select2-result').data 'select2-data' # if @builder.isQuickbuild # @builder.showTooltip 'Quickbuild', exportObj.quickbuildsById[select2_data.id], {ship: @data?.name} if select2_data?.id? # else # @builder.showTooltip 'Pilot', exportObj.wingmatesById[select2_data.id] if select2_data?.id? # @wingmate_selector.on 'mouseover', (e) => # @builder.showTooltip 'Pilot', @wingmate, @ if @wingmate # @wingmate_selector.parent().hide() @points_container = $ @row.find('.points-display-container') @points_container.fadeTo 0, 0 @addon_container = $ @row.find('div.addon-container') @remove_button = $ @row.find('button.remove-pilot') @remove_button.click (e) => e.preventDefault() @row.slideUp 'fast', () => @builder.removeShip this @backend_status?.fadeOut 'slow' @remove_button.hide() @copy_button = $ @row.find('button.copy-pilot') @copy_button.click (e) => clone = @builder.ships[@builder.ships.length - 1] clone.copyFrom(this) @copy_button.hide() @checkPilotSelectorQueryModal() @points_destroyed_button_span = $ @row.find('.destroyed-type') @points_destroyed_button = $ @row.find('button.points-destroyed') @points_destroyed_button.click (e) => if @destroystate == 1 @destroystate = 2 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-crit"></i>' else if @destroystate == 2 @destroystate = 0 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-title"></i>' else @destroystate = 1 @points_destroyed_button_span.html '<i class="xwing-miniatures-font xwing-miniatures-font-hit"></i>' @builder.onPointsUpdated() @points_destroyed_button.hide() teardownUI: -> @row.text '' @row.remove() toString: -> if @pilot? "Pilot #{if @pilot.display_name then @pilot.display_name else @pilot.name} flying #{if @data.display_name then @data.display_name else @data.name}" else "Ship without pilot" toHTML: -> effective_stats = @effectiveStats() action_bar = @builder.formatActions(effective_stats.actions,"&nbsp;&nbsp;", @pilot.keyword ? []) attack_icon = @data.attack_icon ? 'xwing-miniatures-font-frontarc' engagementHTML = if (@pilot.engagement?) then $.trim """ <span class="info-data info-skill">ENG #{@pilot.engagement}</span> """ else '' attackHTML = if (effective_stats.attack?) then $.trim """ <i class="xwing-miniatures-font header-attack #{attack_icon}"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attack ? @data.attack), effective_stats, 'attack')}</span> """ else '' if effective_stats.attackbull? attackbullHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackbull ? @data.attackbull), effective_stats, 'attackbull')}</span>""" else attackbullHTML = '' if effective_stats.attackb? attackbHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackb ? @data.attackb), effective_stats, 'attackb')}</span>""" else attackbHTML = '' if effective_stats.attackf? attackfHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackf ? @data.attackf), effective_stats, 'attackf')}</span>""" else attackfHTML = '' if effective_stats.attackt? attacktHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackt ? @data.attackt), effective_stats, 'attackt')}</span>""" else attacktHTML = '' if effective_stats.attackl? attacklHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-leftarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackl ? @data.attackl), effective_stats, 'attackl')}</span>""" else attacklHTML = '' if effective_stats.attackr? attackrHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-rightarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackr ? @data.attackr), effective_stats, 'attackr')}</span>""" else attackrHTML = '' if effective_stats.attackdt? attackdtHTML = $.trim """<i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i> <span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attackdt ? @data.attackdt), effective_stats, 'attackdt')}</span>""" else attackdtHTML = '' recurringicon = '' if @data.energyrecurr? count = 0 while count < @data.energyrecurr recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count energyHTML = if (@pilot.ship_override?.energy? or @data.energy?) then $.trim """ <i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i> <span class="info-data info-energy">#{statAndEffectiveStat((@pilot.ship_override?.energy ? @data.energy), effective_stats, 'energy')}#{recurringicon}</span> """ else '' forceHTML = if (@pilot.force?) then $.trim """ <i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i> <span class="info-data info-force">#{statAndEffectiveStat((@pilot.ship_override?.force ? @pilot.force), effective_stats, 'force')}<sup><i class="fas fa-caret-up"></i></sup></span> """ else '' if @pilot.charge? recurringicon = '' if @pilot.recurring? if @pilot.recurring > 0 count = 0 while count < @pilot.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = @pilot.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """<i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i><span class="info-data info-charge">#{statAndEffectiveStat((@pilot.ship_override?.charge ? @pilot.charge), effective_stats, 'charge')}#{recurringicon}</span>""" else chargeHTML = '' shieldRECUR = '' if @data.shieldrecurr? count = 0 while count < @data.shieldrecurr shieldRECUR += """<sup><i class="fas fa-caret-up"></i></sup>""" ++count shieldIconHTML = '' if effective_stats.shields for _ in [effective_stats.shields..2] by -1 shieldIconHTML += """<i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield expanded-hull-or-shield"></i>""" shieldIconHTML += """<i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i>""" hullIconHTML = '' if effective_stats.hull for _ in [effective_stats.hull..2] by -1 hullIconHTML += """<i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull expanded-hull-or-shield"></i>""" hullIconHTML += """<i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i>""" html = $.trim """ <div class="fancy-pilot-header"> <div class="pilot-header-text">#{if @pilot.display_name then @pilot.display_name else @pilot.name} <i class="xwing-miniatures-ship xwing-miniatures-ship-#{@data.xws}"></i><span class="fancy-ship-type"> #{if @data.display_name then @data.display_name else @data.name}</span></div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle pilot-points">#{if @quickbuildId != -1 then (if @primary then @getPoints() else '*') else @pilot.points}</div> </div> </div> </div> <div class="fancy-pilot-stats"> <div class="pilot-stats-content"> <span class="info-data info-skill">INI #{statAndEffectiveStat(@pilot.skill, effective_stats, 'skill')}</span> #{engagementHTML} #{attackbullHTML} #{attackHTML} #{attackbHTML} #{attackfHTML} #{attacktHTML} #{attacklHTML} #{attackrHTML} #{attackdtHTML} <i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i> <span class="info-data info-agility">#{statAndEffectiveStat((@pilot.ship_override?.agility ? @data.agility), effective_stats, 'agility')}</span> #{hullIconHTML} <span class="info-data info-hull">#{statAndEffectiveStat((@pilot.ship_override?.hull ? @data.hull), effective_stats, 'hull')}</span> #{shieldIconHTML} <span class="info-data info-shields">#{statAndEffectiveStat((@pilot.ship_override?.shields ? @data.shields), effective_stats, 'shields')}#{shieldRECUR}</span> #{energyHTML} #{forceHTML} #{chargeHTML} <br /> #{action_bar} </div> </div> """ # Maneuver Dials have been moved at the bottom of the squad, rather than beeing added to each ship # dialHTML = @builder.getManeuverTableHTML(effective_stats.maneuvers, @data.maneuvers) # # html += $.trim """ # <div class="fancy-dial"> # #{dialHTML} # </div> # """ if @pilot.text html += $.trim """ <div class="fancy-pilot-text">#{@pilot.text}</div> """ slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 html += $.trim """ <div class="fancy-upgrade-container"> """ for upgrade in slotted_upgrades points = upgrade.getPoints() html += upgrade.toHTML points html += $.trim """ </div> """ HalfPoints = Math.ceil @getPoints() / 2 Threshold = Math.ceil (effective_stats['hull'] + effective_stats['shields']) / 2 html += $.trim """ <div class="ship-points-total"> <strong>Ship Total: #{@getPoints()}, Half Points: #{HalfPoints}, Threshold: #{Threshold}</strong> </div> """ """<div class="fancy-ship">#{html}</div>""" toTableRow: -> table_html = $.trim """ <tr class="simple-pilot"> <td class="name">#{if @pilot.display_name then @pilot.display_name else @pilot.name} &mdash; #{if @data.display_name then @data.display_name else @data.name}</td> <td class="points">#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points}</td> </tr> """ slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades points = upgrade.getPoints() table_html += upgrade.toTableRow points # if @getPoints() != @pilot.points table_html += """<tr class="simple-ship-total"><td colspan="2">Ship Total: #{@getPoints()}</td></tr>""" halfPoints = Math.ceil @getPoints() / 2 threshold = Math.ceil (@effectiveStats()['hull'] + @effectiveStats()['shields']) / 2 table_html += """<tr class="simple-ship-half-points"><td colspan="2">Half Points: #{halfPoints} Threshold: #{threshold}</td></tr>""" table_html += '<tr><td>&nbsp;</td><td></td></tr>' table_html toSimpleCopy: -> simplecopy = """#{@pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points}) \n""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 simplecopy +=" " simplecopy_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_simplecopy = upgrade.toSimpleCopy points simplecopy_upgrades.push upgrade_simplecopy if upgrade_simplecopy? simplecopy += simplecopy_upgrades.join " " simplecopy += """ \n""" halfPoints = Math.ceil @getPoints() / 2 threshold = Math.ceil (@effectiveStats()['hull'] + @effectiveStats()['shields']) / 2 simplecopy += """Ship total: #{@getPoints()} Half Points: #{halfPoints} Threshold: #{threshold} \n \n""" simplecopy toRedditText: -> reddit = """**#{@pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})** \n""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 reddit +=" " reddit_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_reddit = upgrade.toRedditText points reddit_upgrades.push upgrade_reddit if upgrade_reddit? reddit += reddit_upgrades.join " " reddit += """&nbsp;*Ship total: (#{@getPoints()})* \n""" reddit toTTSText: -> tts = """#{exportObj.toTTS(@pilot.name)}""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades upgrade_tts = upgrade.toTTSText() tts += (" + " + upgrade_tts) if upgrade_tts? tts += " / " toBBCode: -> bbcode = """[b]#{if @pilot.display_name then @pilot.display_name else @pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})[/b]""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 bbcode +="\n" bbcode_upgrades= [] for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_bbcode = upgrade.toBBCode points bbcode_upgrades.push upgrade_bbcode if upgrade_bbcode? bbcode += bbcode_upgrades.join "\n" bbcode toSimpleHTML: -> html = """<b>#{if @pilot.display_name then @pilot.display_name else @pilot.name} (#{if @quickbuildId != -1 then (if @primary then exportObj.quickbuildsById[@quickbuildId].threat else 0) else @pilot.points})</b><br />""" slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?) if slotted_upgrades.length > 0 for upgrade in slotted_upgrades points = upgrade.getPoints() upgrade_html = upgrade.toSimpleHTML points html += upgrade_html if upgrade_html? html toSerialized: -> # PILOT_ID:UPGRADEID1,UPGRADEID2:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2 if @builder.isQuickbuild if (!@wingmates? || @wingmates.length == 0) then """#{@quickbuildId}X""" else """#{@quickbuildId}X#{@wingmates.length}""" else upgrades = """#{upgrade?.data?.id ? "" for upgrade, i in @upgrades}""".replace(/,/g, "W") [ @pilot.id, upgrades, ].join 'X' fromSerialized: (version, serialized) -> # adds a ship from the given serialized data to the squad. # returns true, if all upgrades have been added successfully, false otherwise # returning false does not necessary mean nothing has been added, but some stuff might have been dropped (e.g. 0-0-0 if vader is not yet in the squad) everythingadded = true switch version # version 1-3 are 1st edition x-wing only, so we may as well delete them. # version 4 was the final version of 1st edition, and the first few weeks of 2nd edition. # version 5 is the current version. It handles titles and mods as regular upgrades. when 4, 5, 6 # PILOT_ID:UPGRADEID1,UPGRADEID2:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2 # conferredaddons are upgrade slots added by e.g. titles # version 5 is the same as version 4, but title and mod has been dropped (as they are treated as upgrades anyways). Thus, we may differ by length if (serialized.split ':').length == 3 # version 5,6 [ pilot_id, upgrade_ids, conferredaddon_pairs ] = serialized.split ':' else # version 4 [ pilot_id, upgrade_ids, version_4_compatibility_placeholder_title, version_4_compatibility_placeholder_mod, conferredaddon_pairs ] = serialized.split ':' @setPilotById parseInt(pilot_id), true # make sure the pilot is valid return false unless @validate deferred_ids = [] for upgrade_id, i in upgrade_ids.split ',' upgrade_id = parseInt upgrade_id continue if upgrade_id < 0 or isNaN(upgrade_id) # Defer fat upgrades if @upgrades[i].isOccupied() or @upgrades[i].dataById[upgrade_id]?.also_occupies_upgrades? deferred_ids.push upgrade_id else @upgrades[i].setById upgrade_id everythingadded &= @upgrades[i].lastSetValid for deferred_id in deferred_ids deferred_id_added = false for upgrade, i in @upgrades if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot continue upgrade.setById deferred_id deferred_id_added = upgrade.lastSetValid break everythingadded &= deferred_id_added if conferredaddon_pairs? conferredaddon_pairs = conferredaddon_pairs.split ',' else conferredaddon_pairs = [] for upgrade in @upgrades if upgrade?.data? and upgrade.conferredAddons.length > 0 upgrade_conferred_addon_pairs = conferredaddon_pairs.splice 0, upgrade.conferredAddons.length for conferredaddon_pair, i in upgrade_conferred_addon_pairs [ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.' addon_id = parseInt addon_id addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized] if not addon_cls console.log("Something went wrong... could not serialize properly") continue conferred_addon = upgrade.conferredAddons[i] if conferred_addon instanceof addon_cls conferred_addon.setById addon_id everythingadded &= conferred_addon.lastSetValid else throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there") when 7, 8 pilot_splitter = if version > 7 then 'X' else ':' upgrade_splitter = if version > 7 then 'W' else ',' # version 7 is an further extension of version 6, allowing arbitrary order of upgrades. It currently ignores conferredaddons (upgrades in slots added by titles etc), probably we can drop the special case handling for them and include them into the usual upgrade list? [ pilot_id, upgrade_ids, conferredaddon_pairs ] = serialized.split pilot_splitter upgrade_ids = upgrade_ids.split upgrade_splitter # set the pilot @setPilotById parseInt(pilot_id), true # make sure the pilot is valid return false unless @validate if !@builder.isQuickbuild # iterate over upgrades to be added, and remove all that have been successfully added for _ in [1 ... 3] # try adding each upgrade a few times, as the required slots might be added in by titles etc and are not yet available on the first try for i in [upgrade_ids.length - 1 ... -1] upgrade_id = upgrade_ids[i] upgrade = exportObj.upgradesById[upgrade_id] if not upgrade? upgrade_ids.splice(i,1) # Remove unknown or empty ID if upgrade_id != "" console.log("Unknown upgrade id " + upgrade_id + " could not be added. Please report that error") everythingadded = false continue for upgrade_selection in @upgrades if exportObj.slotsMatching(upgrade.slot, upgrade_selection.slot) and not upgrade_selection.isOccupied() upgrade_selection.setById upgrade_id if upgrade_selection.lastSetValid upgrade_ids.splice(i,1) # added successfully, remove from list break else # we are in quickbuild. Number of wingmates might be provided as upgrade ID of a quickbuild if upgrade_ids.length > 0 && @wingmates.length > 0 # check if we are actually a wingleader @setWingmates(upgrade_ids[0]) everythingadded &= upgrade_ids.length == 0 @updateSelections() everythingadded effectiveStats: -> stats = attack: @pilot.ship_override?.attack ? @data.attack attackf: @pilot.ship_override?.attackf ? @data.attackf attackbull: @pilot.ship_override?.attackbull ? @data.attackbull attackb: @pilot.ship_override?.attackb ? @data.attackb attackt: @pilot.ship_override?.attackt ? @data.attackt attackl: @pilot.ship_override?.attackl ? @data.attackl attackr: @pilot.ship_override?.attackr ? @data.attackr attackdt: @pilot.ship_override?.attackdt ? @data.attackdt energy: @pilot.ship_override?.energy ? @data.energy agility: @pilot.ship_override?.agility ? @data.agility hull: @pilot.ship_override?.hull ? @data.hull shields: @pilot.ship_override?.shields ? @data.shields force: (@pilot.ship_override?.force ? @pilot.force) ? 0 charge: @pilot.ship_override?.charge ? @pilot.charge actions: (@pilot.ship_override?.actions ? @data.actions).slice 0 # need a deep copy of maneuvers array stats.maneuvers = [] for s in [0 ... (@data.maneuvers ? []).length] stats.maneuvers[s] = @data.maneuvers[s].slice 0 # Droid conversion of Focus to Calculate if @pilot.keyword? and ("Droid" in @pilot.keyword) and stats.actions? new_stats = [] for statentry in stats.actions new_stats.push statentry.replace("Focus","Calculate") stats.actions = new_stats for upgrade in @upgrades upgrade.data.modifier_func(stats) if upgrade?.data?.modifier_func? @pilot.modifier_func(stats) if @pilot?.modifier_func? stats validate: -> # Remove addons that violate their validation functions (if any) one by one # until everything checks out # If there is no explicit validation_func, use restriction_func # Returns true, if nothing has been changed, and false otherwise # check if we are an empty selection, which is always valid if not @pilot? return true unchanged = true max_checks = 32 # that's a lot of addons if @builder.isEpic #Command Epic adding if not ("Command" in @pilot.slots) addCommand = true for upgrade in @upgrades if ("Command" == upgrade.slot) and (this == upgrade.ship) addCommand = false if addCommand == true @upgrades.push new exportObj.Upgrade ship: this container: @addon_container slot: "Command" else if !@builder.isQuickbuild #cleanup Command upgrades for i in [@upgrades.length - 1 ... -1] upgrade = @upgrades[i] if upgrade.slot == "Command" upgrade.destroy $.noop @upgrades.splice i,1 for i in [0...max_checks] valid = true pilot_func = @pilot?.validation_func ? @pilot?.restriction_func ? undefined if (pilot_func? and not pilot_func(this, @pilot)) or not (@builder.isItemAvailable(@pilot, true)) # we go ahead and happily remove ourself. Of course, when calling a method like validate on an object, you have to expect that it will dissappear, right? @builder.removeShip this return false # no need to check anything further, as we do not exist anymore # everything is limited in X-Wing 2.0, so we need to check if any upgrade is equipped more than once equipped_upgrades = [] for upgrade in @upgrades func = upgrade?.data?.validation_func ? undefined if func? func_result = upgrade?.data?.validation_func(this, upgrade) else if upgrade?.data?.restrictions func_result = @restriction_check(upgrade.data.restrictions, upgrade) # check if either a) validation func not met or b) upgrade already equipped (in 2.0 everything is limited) or c) upgrade is not available (e.g. not Hyperspace legal) # ignore those checks if this is a quickbuild squad, as quickbuild does whatever it wants to do... if ((func_result? and not func_result) or (upgrade?.data? and (upgrade.data in equipped_upgrades or (upgrade.data.faction? and not @builder.isOurFaction(upgrade.data.faction,@pilot.faction)) or not @builder.isItemAvailable(upgrade.data)))) and not @builder.isQuickbuild #console.log "Invalid upgrade: #{upgrade?.data?.name}" upgrade.setById null valid = false unchanged = false break if upgrade?.data? and upgrade.data equipped_upgrades.push(upgrade?.data) break if valid @updateSelections() unchanged checkUnreleasedContent: -> if @pilot? and not exportObj.isReleased @pilot #console.log "#{@pilot.name} is unreleased" return true for upgrade in @upgrades if upgrade?.data? and not exportObj.isReleased upgrade.data #console.log "#{upgrade.data.id} is unreleased" return true false hasAnotherUnoccupiedSlotLike: (upgrade_obj, upgradeslot) -> for upgrade in @upgrades continue if upgrade == upgrade_obj or upgrade.slot != upgradeslot return true unless upgrade.isOccupied() false restriction_check: (restrictions, upgrade_obj) -> effective_stats = @effectiveStats() for r in restrictions if r[0] == "orUnique" if @checkListForUnique(r[1].toLowerCase().replace(/[^0-9a-z]/gi, '').replace(/\s+/g, '-')) return true switch r[0] when "Base" switch r[1] when "Small" if @data.medium? or @data.large? or @data.huge? then return false when "Small or Medium" if @data.large? or @data.huge? then return false when "Medium" if not (@data.medium?) then return false when "Medium or Large" if not (@data.medium? or @data.large?) then return false when "Large" if not (@data.large?) then return false when "Huge" if not (@data.huge?) then return false when "Standard" if @data.huge? then return false when "Action" if not ((r[1] in effective_stats.actions) or ("*#{r[1]}" in effective_stats.actions) or ("F-#{r[1]}" in effective_stats.actions) or ("R-#{r[1]}" in effective_stats.actions)) then return false when "Keyword" if not (@checkKeyword(r[1])) then return false when "Equipped" if not ((@doesSlotExist(r[1]) and not @hasAnotherUnoccupiedSlotLike(upgrade_obj, r[1]))) then return false when "Slot" if not @hasAnotherUnoccupiedSlotLike(upgrade_obj, r[1]) then return false when "AttackArc" if not @data.attackb? then return false when "ShieldsGreaterThan" if not (@data.shields > r[1]) then return false when "EnergyGreatterThan" if not (effective_stats.energy > r[1]) then return false when "InitiativeGreaterThan" if not (@pilot.skill > r[1]) then return false when "InitiativeLessThan" if not (@pilot.skill < r[1]) then return false when "AgilityEquals" if not (effective_stats.agility == r[1]) then return false when "isUnique" if r[1] != @pilot.unique? then return false when "Format" switch r[1] when "Epic" if not (@data.name in exportObj.epicExclusionsList) then return false when "Standard" if @data.name in exportObj.epicExclusionsList then return false when "Faction" if @pilot.faction != r[1] then return false return true doesSlotExist: (slot) -> for upgrade in @upgrades if slot == upgrade.slot return true false isSlotOccupied: (slot_name) -> for upgrade in @upgrades if exportObj.slotsMatching(upgrade.slot, slot_name) return true unless upgrade.isOccupied() false checkKeyword: (keyword) -> if @data.name?.includes(keyword) return true for words in @data.keyword ? [] if words == keyword return true for words in @pilot.keyword ? [] if words == keyword return true for upgrade in @upgrades for word in upgrade?.data?.keyword ? [] if word == keyword return true false checkListForUnique: (name) -> for t, things of @builder.uniques_in_use if t != 'Slot' return true if name in (thing.canonical_name.getXWSBaseName() for thing in things) false toXWS: -> xws = id: (@pilot.xws ? @pilot.canonical_name) name: (@pilot.xws ? @pilot.canonical_name) # name is no longer part of xws 2.0.0, and was replaced by id. However, we will add it here for some kind of backward compatibility. May be removed, as soon as everybody is using id. points: @getPoints() #ship: @data.canonical_name ship: @data.xws.canonicalize() if @data.multisection xws.multisection = @data.multisection.slice 0 upgrade_obj = {} for upgrade in @upgrades if upgrade?.data? upgrade.toXWS upgrade_obj if Object.keys(upgrade_obj).length > 0 xws.upgrades = upgrade_obj xws getConditions: -> if Set? conditions = new Set() if @pilot?.applies_condition? if @pilot.applies_condition instanceof Array for condition in @pilot.applies_condition conditions.add(exportObj.conditionsByCanonicalName[condition]) else conditions.add(exportObj.conditionsByCanonicalName[@pilot.applies_condition]) for upgrade in @upgrades if upgrade?.data?.applies_condition? if upgrade.data.applies_condition instanceof Array for condition in upgrade.data.applies_condition conditions.add(exportObj.conditionsByCanonicalName[condition]) else conditions.add(exportObj.conditionsByCanonicalName[upgrade.data.applies_condition]) conditions else console.warn 'Set not supported in this JS implementation, not implementing conditions' [] class GenericAddon constructor: (args) -> # args @ship = args.ship @container = $ args.container # internal state @data = null @unadjusted_data = null @conferredAddons = [] @serialization_code = 'X' @occupied_by = null @occupying = [] @destroyed = false # Overridden by children @type = null @dataByName = null @dataById = null @adjustment_func = args.adjustment_func if args.adjustment_func? @filter_func = args.filter_func if args.filter_func? @placeholderMod_func = if args.placeholderMod_func? then args.placeholderMod_func else (x) => x destroy: (cb, args...) -> return cb(args) if @destroyed if @data?.unique? await @ship.builder.container.trigger 'xwing:releaseUnique', [ @data, @type, defer() ] if @data?.standardized? @removeStandardized() @destroyed = true @rescindAddons() @deoccupyOtherUpgrades() @selector.select2 'destroy' @selectorwrap.remove() cb args setupSelector: (args) -> @selectorwrap = $ document.createElement 'div' @selectorwrap.addClass 'form-group d-flex upgrade-box' @selector = $ document.createElement 'INPUT' @selector.attr 'type', 'hidden' @selectorwrap.append @selector @selectorwrap.append $.trim ''' <div class="input-group-addon"> <button class="btn btn-secondary d-block d-md-none upgrade-query-modal"><i class="fas fa-question"></i></button> </div> ''' @upgrade_query_modal = $ @selectorwrap.find('button.upgrade-query-modal') @container.append @selectorwrap args.minimumResultsForSearch = -1 if $.isMobile() args.formatResultCssClass = (obj) => if @ship.builder.collection? not_in_collection = false if obj.id == @data?.id # Currently selected card; mark as not in collection if it's neither # on the shelf nor on the table unless (@ship.builder.collection.checkShelf(@type.toLowerCase(), obj.name) or @ship.builder.collection.checkTable(@type.toLowerCase(), obj.name)) not_in_collection = true else # Not currently selected; check shelf only not_in_collection = not @ship.builder.collection.checkShelf(@type.toLowerCase(), obj.name) if not_in_collection then 'select2-result-not-in-collection' else '' else '' args.formatSelection = (obj, container) => icon = switch @type when 'Upgrade' @slot.toLowerCase().replace(/[^0-9a-z]/gi, '') else @type.toLowerCase().replace(/[^0-9a-z]/gi, '') icon = icon.replace("configuration", "config") .replace("force", "forcepower") # Append directly so we don't have to disable markup escaping $(container).append """<i class="xwing-miniatures-font xwing-miniatures-font-#{icon}"></i> #{obj.text}""" # If you return a string, Select2 will render it undefined @selector.select2 args @upgrade_query_modal.click (e) => if @data console.log "#{@data.name}" @ship.builder.showTooltip 'Addon', @data, ({addon_type: @type} if @data?) , @ship.builder.mobile_tooltip_modal, true @ship.builder.mobile_tooltip_modal.modal 'show' @selector.on 'select2-focus', (e) => if $.isMobile() $('.select2-container .select2-focusser').remove() $('.select2-search input').prop('focus',false).removeClass('select2-focused') @selector.on 'change', (e) => @setById @selector.select2('val') @ship.builder.current_squad.dirty = true @ship.builder.container.trigger 'xwing-backend:squadDirtinessChanged' @ship.builder.backend_status.fadeOut 'slow' @selector.data('select2').results.on 'mousemove-filtered', (e) => select2_data = $(e.target).closest('.select2-result').data 'select2-data' @ship.builder.showTooltip 'Addon', @dataById[select2_data.id], {addon_type: @type} if select2_data?.id? @selector.data('select2').container.on 'mouseover', (e) => @ship.builder.showTooltip 'Addon', @data, {addon_type: @type} if @data? setById: (id) -> @setData @dataById[parseInt id] setByName: (name) -> @setData @dataByName[$.trim name] setData: (new_data) -> if new_data?.id != @data?.id if @data?.unique? or @data?.solitary? await @ship.builder.container.trigger 'xwing:releaseUnique', [ @unadjusted_data, @type, defer() ] if @data?.standardized? @removeStandardized() @rescindAddons() @deoccupyOtherUpgrades() if new_data?.unique? or new_data?.solitary? try await @ship.builder.container.trigger 'xwing:claimUnique', [ new_data, @type, defer() ] catch alreadyClaimed @ship.builder.container.trigger 'xwing:pointsUpdated' @lastSetValid = false return # Need to make a copy of the data, but that means I can't just check equality @data = @unadjusted_data = new_data if @data? if @data.superseded_by_id return @setById @data.superseded_by_id if @adjustment_func? @data = @adjustment_func(@data) @unequipOtherUpgrades() @occupyOtherUpgrades() @conferAddons() if @data.standardized? @addToStandardizedList() else @deoccupyOtherUpgrades() # this will remove not allowed upgrades (is also done on pointsUpdated). We do it explicitly so we can tell if the setData was successfull @lastSetValid = @ship.validate() @ship.builder.container.trigger 'xwing:pointsUpdated' addToStandardizedList: -> # check first if standard combo exists and return if it does idx = @ship.builder.standard_list['Ship'].indexOf @ship.data.name if idx > -1 if @ship.builder.standard_list['Upgrade'][idx]?.name == @data.name return @ship.builder.standard_list['Upgrade'].push @data @ship.builder.standard_list['Ship'].push @ship.data.name removeStandardized: -> # removes the ship upgrade combo from the stanard list array idx = @ship.builder.standard_list['Ship'].indexOf @ship.data.name if idx > -1 if @ship.builder.standard_list['Upgrade'][idx]?.name == @data.name @ship.builder.standard_list['Upgrade'].splice idx,1 @ship.builder.standard_list['Ship'].splice idx,1 # now remove all upgrades of the same name nameToRemove = @data.name for ship in @ship.builder.ships if ship.data?.name == @ship.data.name for upgrade in ship.upgrades if upgrade.data?.name == nameToRemove upgrade.data = null conferAddons: -> if @data.confersAddons? and !@ship.builder.isQuickbuild and @data.confersAddons.length > 0 for addon in @data.confersAddons cls = addon.type args = ship: @ship container: @container args.slot = addon.slot if addon.slot? args.adjustment_func = addon.adjustment_func if addon.adjustment_func? args.filter_func = addon.filter_func if addon.filter_func? args.auto_equip = addon.auto_equip if addon.auto_equip? args.placeholderMod_func = addon.placeholderMod_func if addon.placeholderMod_func? addon = new cls args if addon instanceof exportObj.Upgrade @ship.upgrades.push addon else throw new Error("Unexpected addon type for addon #{addon}") @conferredAddons.push addon rescindAddons: -> await for addon in @conferredAddons addon.destroy defer() for addon in @conferredAddons if addon instanceof exportObj.Upgrade @ship.upgrades.removeItem addon else throw new Error("Unexpected addon type for addon #{addon}") @conferredAddons = [] getPoints: (data = @data, ship = @ship) -> # Moar special case jankiness if data?.variableagility? data?.pointsarray[ship.data.agility] else if data?.variablebase? if ship?.data.medium? data?.pointsarray[1] else if ship?.data.large? data?.pointsarray[2] else if ship?.data.huge? data?.pointsarray[3] else data?.pointsarray[0] else if data?.variableinit? data?.pointsarray[ship.pilot.skill] else data?.points ? 0 updateSelection: (points) -> if @data? @selector.select2 'data', id: @data.id text: "#{if @data.display_name then @data.display_name else @data.name} (#{points}#{if @data.pointsarray then '*' else ''})" else @selector.select2 'data', null toString: -> if @data? "#{if @data.display_name then @data.display_name else @data.name} (#{@getPoints()})" else "No #{@type}" toHTML: (points) -> if @data? if @data.slot? and @data.slot == "HardpointShip" upgrade_slot_font = "hardpoint" else upgrade_slot_font = (@data.slot ? @type).toLowerCase().replace(/[^0-9a-z]/gi, '') match_array = @data.text?match(/(<span.*<\/span>)<br \/><br \/>(.*)/) if match_array restriction_html = '<div class="card-restriction-container">' + match_array[1] + '</div>' text_str = match_array[2] else restriction_html = '' text_str = @data.text attackHTML = "" if @data.range? attackrangebonus = if (@data.rangebonus?) then """<span class="upgrade-attack-rangebonus"><i class="xwing-miniatures-font xwing-miniatures-font-rangebonusindicator"></i></span>""" else '' attackStats = $.trim """ <span class="upgrade-attack-range">#{@data.range}</span> #{attackrangebonus} """ attackIcon = if (@data.attack?) then $.trim """ <span class="info-data info-attack">#{@data.attack}</span> <i class="xwing-miniatures-font xwing-miniatures-font-frontarc"></i> """ else if (@data.attackt?) then $.trim """ <span class="info-data info-attack">#{@data.attackt}</span> <i class="xwing-miniatures-font xwing-miniatures-font-singleturretarc"></i> """ else if (@data.attackdt?) then $.trim """ <span class="info-data info-attack">#{@data.attackdt}</span> <i class="xwing-miniatures-font xwing-miniatures-font-doubleturretarc"></i> """ else if (@data.attackl?) then $.trim """ <span class="info-data info-attack">#{@data.attackl}</span> <i class="xwing-miniatures-font xwing-miniatures-font-leftarc"></i> """ else if (@data.attackr?) then $.trim """ <span class="info-data info-attack">#{@data.attackr}</span> <i class="xwing-miniatures-font xwing-miniatures-font-rightarc"></i> """ else if (@data.attackbull?) then $.trim """ <span class="info-data info-attack">#{@data.attackbull}</span> <i class="xwing-miniatures-font xwing-miniatures-font-bullseyearc"></i> """ else '' attackHTML = $.trim """ <div class="upgrade-attack"> #{attackStats} #{attackIcon} </div> """ if @data.charge? recurringicon = '' if @data.recurring? if @data.recurring > 0 count = 0 while count < @data.recurring recurringicon += '<sup><i class="fas fa-caret-up"></i></sup>' ++count else count = @data.recurring while count < 0 recurringicon += '<sub><i class="fas fa-caret-down"></i></sub>' ++count chargeHTML = $.trim """ <div class="upgrade-charge"> <span class="info-data info-charge">#{@data.charge}</span> <i class="xwing-miniatures-font xwing-miniatures-font-charge"></i>#{recurringicon} </div> """ else chargeHTML = $.trim '' if (@data.force?) forceHTML = $.trim """ <div class="upgrade-force"> <span class="info-data info-force">#{@data.force}</span> <i class="xwing-miniatures-font xwing-miniatures-font-forcecharge"></i><sup><i class="fas fa-caret-up"></i></sup> </div> """ else forceHTML = $.trim '' $.trim """ <div class="upgrade-container"> <div class="upgrade-stats"> <div class="upgrade-name"><i class="xwing-miniatures-font xwing-miniatures-font-#{upgrade_slot_font}"></i>#{if @data.display_name then @data.display_name else @data.name}</div> <div class="mask"> <div class="outer-circle"> <div class="inner-circle upgrade-points">#{points}</div> </div> </div> #{restriction_html} </div> #{attackHTML} #{chargeHTML} #{forceHTML} <div class="upgrade-text">#{text_str}</div> <div style="clear: both;"></div> </div> """ else '' toTableRow: (points) -> if @data? $.trim """ <tr class="simple-addon"> <td class="name">#{if @data.display_name then @data.display_name else @data.name}</td> <td class="points">#{points}</td> </tr> """ else '' toSimpleCopy: (points) -> if @data? """#{@data.name} (#{points}) \n""" else null toRedditText: (points) -> if @data? """*&nbsp;#{@data.name} (#{points})* \n""" else null toTTSText: () -> if @data? """#{exportObj.toTTS(@data.name)}""" else null toBBCode: (points) -> if @data? """[i]#{if @data.display_name then @data.display_name else @data.name} (#{points})[/i]""" else null toSimpleHTML: (points) -> if @data? """<i>#{if @data.display_name then @data.display_name else @data.name} (#{points})</i><br />""" else '' toSerialized: -> """#{@serialization_code}.#{@data?.id ? -1}""" unequipOtherUpgrades: -> for slot in @data?.unequips_upgrades ? [] for upgrade in @ship.upgrades continue if upgrade.slot != slot or upgrade == this or not upgrade.isOccupied() upgrade.setData null break isOccupied: -> @data? or @occupied_by? occupyOtherUpgrades: -> for slot in @data?.also_occupies_upgrades ? [] for upgrade in @ship.upgrades continue if upgrade.slot != slot or upgrade == this or upgrade.isOccupied() @occupy upgrade break deoccupyOtherUpgrades: -> for upgrade in @occupying @deoccupy upgrade occupy: (upgrade) -> upgrade.occupied_by = this upgrade.selector.select2 'enable', false @occupying.push upgrade deoccupy: (upgrade) -> upgrade.occupied_by = null upgrade.selector.select2 'enable', true occupiesAnUpgradeSlot: (upgradeslot) -> for upgrade in @ship.upgrades continue if upgrade.slot != upgradeslot or upgrade == this or upgrade.data? if upgrade.occupied_by? and upgrade.occupied_by == this return true false toXWS: (upgrade_dict) -> (upgrade_dict[exportObj.toXWSUpgrade[@data.slot] ? @data.slot.canonicalize()] ?= []).push (@data.xws ? @data.canonical_name) class exportObj.Upgrade extends GenericAddon constructor: (args) -> # args super args @slot = args.slot @type = 'Upgrade' @dataById = exportObj.upgradesById @dataByName = exportObj.upgrades @serialization_code = 'U' @setupSelector() setupSelector: -> super width: '100%' placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'upgradePlaceholder', @slot) allowClear: true query: (query) => data = {results: []} data.results = @ship.builder.getAvailableUpgradesIncluding(@slot, @data, @ship, this, query.term, @filter_func) query.callback(data) class exportObj.RestrictedUpgrade extends exportObj.Upgrade constructor: (args) -> @filter_func = args.filter_func super args @serialization_code = 'u' if args.auto_equip? @setById args.auto_equip class exportObj.QuickbuildUpgrade extends GenericAddon constructor: (args) -> super args @slot = args.slot @type = 'Upgrade' @dataById = exportObj.upgradesById @dataByName = exportObj.upgrades @serialization_code = 'U' @upgrade = args.upgrade @setupSelector() setupSelector: -> super width: '100%' allowClear: false query: (query) => data = { results: [{ id: @upgrade.id text: if @upgrade.display_name then @upgrade.display_name else @upgrade.name points: 0 name: @upgrade.name display_name: @upgrade.display_name }] } query.callback(data) getPoints: (args) -> 0 updateSelection: (args) -> if @data? @selector.select2 'data', id: @data.id text: "#{if @data.display_name then @data.display_name else @data.name}" else @selector.select2 'data', null SERIALIZATION_CODE_TO_CLASS = 'U': exportObj.Upgrade 'u': exportObj.RestrictedUpgrade
[ { "context": "ame: 1, modelYear: 1 }, { unique: true })\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass Airc", "end": 327, "score": 0.999836802482605, "start": 315, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/schema/AircraftModelSchema.coffee
qrefdev/qref
0
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId ### Schema representing a specific aircraft make and model. @example MongoDB Collection db.aircraft.models @example MongoDB Indexes db.aircraft.models.ensureIndex({ name: 1, modelYear: 1 }, { unique: true }) @author Nathan Klick @copyright QRef 2012 @abstract ### class AircraftModelSchemaInternal ### @property [String] (Required) The name of the model. ### name: type: String required: true ### @property [String] (Optional) A detailed description of the model. ### description: type: String required: false ### @property [ObjectId] (Required) The associated manufacturer of this model. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId required: true ref: 'aircraft.manufacturers' ### @property [String] (Required) A string representing the specific year of this model. ### modelYear: type: String required: true AircraftModelSchema = new Schema(new AircraftModelSchemaInternal()) AircraftModelSchema.index({ name: 1, modelYear: 1}) module.exports = AircraftModelSchema
97864
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId ### Schema representing a specific aircraft make and model. @example MongoDB Collection db.aircraft.models @example MongoDB Indexes db.aircraft.models.ensureIndex({ name: 1, modelYear: 1 }, { unique: true }) @author <NAME> @copyright QRef 2012 @abstract ### class AircraftModelSchemaInternal ### @property [String] (Required) The name of the model. ### name: type: String required: true ### @property [String] (Optional) A detailed description of the model. ### description: type: String required: false ### @property [ObjectId] (Required) The associated manufacturer of this model. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId required: true ref: 'aircraft.manufacturers' ### @property [String] (Required) A string representing the specific year of this model. ### modelYear: type: String required: true AircraftModelSchema = new Schema(new AircraftModelSchemaInternal()) AircraftModelSchema.index({ name: 1, modelYear: 1}) module.exports = AircraftModelSchema
true
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId ### Schema representing a specific aircraft make and model. @example MongoDB Collection db.aircraft.models @example MongoDB Indexes db.aircraft.models.ensureIndex({ name: 1, modelYear: 1 }, { unique: true }) @author PI:NAME:<NAME>END_PI @copyright QRef 2012 @abstract ### class AircraftModelSchemaInternal ### @property [String] (Required) The name of the model. ### name: type: String required: true ### @property [String] (Optional) A detailed description of the model. ### description: type: String required: false ### @property [ObjectId] (Required) The associated manufacturer of this model. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId required: true ref: 'aircraft.manufacturers' ### @property [String] (Required) A string representing the specific year of this model. ### modelYear: type: String required: true AircraftModelSchema = new Schema(new AircraftModelSchemaInternal()) AircraftModelSchema.index({ name: 1, modelYear: 1}) module.exports = AircraftModelSchema
[ { "context": "#!/usr/bin/env coffee\n\n# Copyright (c) Konode. All rights reserved.\n# This source code is su", "end": 42, "score": 0.7492069005966187, "start": 39, "tag": "USERNAME", "value": "Kon" }, { "context": "#!/usr/bin/env coffee\n\n# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 45, "score": 0.5282942652702332, "start": 42, "tag": "NAME", "value": "ode" }, { "context": "aDirectory: dataDir\n}\n\nUsers.Account.read backend, userName, (err, account) =>\n\tif err\n\t\tconsole.error err.st", "end": 1091, "score": 0.9598888158798218, "start": 1083, "tag": "USERNAME", "value": "userName" } ]
scripts/decrypt.coffee
LogicalOutcomes/KoNote
1
#!/usr/bin/env coffee # Copyright (c) Konode. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Use this script from a command line. # Pipe encrypted data into stdin, and it will output decrypted data on stdout. # Alternatively, specify a file path, and it will read the encrypted data, and # output decrypted data on stdout. # # Example: # scripts/decrypt.coffee data user pw data/clientFiles/some-encrypted-file Fs = require 'fs' {SymmetricEncryptionKey} = require '../src/persist/crypto' Users = require '../src/persist/users' if process.argv.length not in [5, 6] console.error "Usage: <command> <data_directory> <user_name> <password> [<encrypted_file>]" console.error "If encrypted_file is omitted, data will be read from stdin." return dataDir = process.argv[2] userName = process.argv[3] password = process.argv[4] encryptedFile = process.argv[5] backend = { type: 'file-system' dataDirectory: dataDir } Users.Account.read backend, userName, (err, account) => if err console.error err.stack return account.decryptWithPassword password, (err, decryptedAccount) => if err console.error err.stack return globalEncryptionKey = SymmetricEncryptionKey.import decryptedAccount.privateInfo.globalEncryptionKey readEncryptedFile (err, encryptedInput) => if err console.error err.stack return process.stdout.write globalEncryptionKey.decrypt encryptedInput readEncryptedFile = (cb) => if encryptedFile cb null, Fs.readFileSync encryptedFile return inputBufs = [] process.stdin.on 'readable', => chunkBuf = process.stdin.read() if chunkBuf isnt null inputBufs.push chunkBuf process.stdin.on 'end', => encryptedInput = Buffer.concat inputBufs cb null, encryptedInput
117297
#!/usr/bin/env coffee # Copyright (c) Kon<NAME>. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Use this script from a command line. # Pipe encrypted data into stdin, and it will output decrypted data on stdout. # Alternatively, specify a file path, and it will read the encrypted data, and # output decrypted data on stdout. # # Example: # scripts/decrypt.coffee data user pw data/clientFiles/some-encrypted-file Fs = require 'fs' {SymmetricEncryptionKey} = require '../src/persist/crypto' Users = require '../src/persist/users' if process.argv.length not in [5, 6] console.error "Usage: <command> <data_directory> <user_name> <password> [<encrypted_file>]" console.error "If encrypted_file is omitted, data will be read from stdin." return dataDir = process.argv[2] userName = process.argv[3] password = process.argv[4] encryptedFile = process.argv[5] backend = { type: 'file-system' dataDirectory: dataDir } Users.Account.read backend, userName, (err, account) => if err console.error err.stack return account.decryptWithPassword password, (err, decryptedAccount) => if err console.error err.stack return globalEncryptionKey = SymmetricEncryptionKey.import decryptedAccount.privateInfo.globalEncryptionKey readEncryptedFile (err, encryptedInput) => if err console.error err.stack return process.stdout.write globalEncryptionKey.decrypt encryptedInput readEncryptedFile = (cb) => if encryptedFile cb null, Fs.readFileSync encryptedFile return inputBufs = [] process.stdin.on 'readable', => chunkBuf = process.stdin.read() if chunkBuf isnt null inputBufs.push chunkBuf process.stdin.on 'end', => encryptedInput = Buffer.concat inputBufs cb null, encryptedInput
true
#!/usr/bin/env coffee # Copyright (c) KonPI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Use this script from a command line. # Pipe encrypted data into stdin, and it will output decrypted data on stdout. # Alternatively, specify a file path, and it will read the encrypted data, and # output decrypted data on stdout. # # Example: # scripts/decrypt.coffee data user pw data/clientFiles/some-encrypted-file Fs = require 'fs' {SymmetricEncryptionKey} = require '../src/persist/crypto' Users = require '../src/persist/users' if process.argv.length not in [5, 6] console.error "Usage: <command> <data_directory> <user_name> <password> [<encrypted_file>]" console.error "If encrypted_file is omitted, data will be read from stdin." return dataDir = process.argv[2] userName = process.argv[3] password = process.argv[4] encryptedFile = process.argv[5] backend = { type: 'file-system' dataDirectory: dataDir } Users.Account.read backend, userName, (err, account) => if err console.error err.stack return account.decryptWithPassword password, (err, decryptedAccount) => if err console.error err.stack return globalEncryptionKey = SymmetricEncryptionKey.import decryptedAccount.privateInfo.globalEncryptionKey readEncryptedFile (err, encryptedInput) => if err console.error err.stack return process.stdout.write globalEncryptionKey.decrypt encryptedInput readEncryptedFile = (cb) => if encryptedFile cb null, Fs.readFileSync encryptedFile return inputBufs = [] process.stdin.on 'readable', => chunkBuf = process.stdin.read() if chunkBuf isnt null inputBufs.push chunkBuf process.stdin.on 'end', => encryptedInput = Buffer.concat inputBufs cb null, encryptedInput
[ { "context": ".watsonplatform.net/tone-analyzer/api'\n username: watsonCredentials.username\n password: watsonCredentials.password\n version_", "end": 355, "score": 0.9160674214363098, "start": 329, "tag": "USERNAME", "value": "watsonCredentials.username" }, { "context": " username: watsonCredentials.username\n password: watsonCredentials.password\n version_date: '2016-11-02'\n version: 'v3'\n}\n\nn", "end": 394, "score": 0.9990957379341125, "start": 368, "tag": "PASSWORD", "value": "watsonCredentials.password" } ]
server-side-source/api-routes/tone-api.coffee
Lissy93/twitter-sentiment-visualisation-
155
express = require('express') router = express.Router() fetchSentimentTweets = require '../utils/fetch-sentiment-tweets' watson = require 'watson-developer-cloud' watsonCredentials = require('../config/keys').watson toneAnalyzer = watson.tone_analyzer { url: 'https://gateway.watsonplatform.net/tone-analyzer/api' username: watsonCredentials.username password: watsonCredentials.password version_date: '2016-11-02' version: 'v3' } noBodyProvided = (req, res, next) -> makeBody = (twAr) -> tweetBody = '' for tw in twAr then tweetBody += tw.body + ' ' tweetBody = tweetBody.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '') tweetBody = tweetBody.replace(/[^A-Za-z0-9 ]/g, '').substring(0, 5000) toneRes = (body) -> toneAnalyzer.tone {text: body}, (err, data) -> if err then next err else res.json data if req.body.searchTerm? && req.body.searchTerm != '' fetchSentimentTweets req.body.searchTerm, (r) -> toneRes makeBody r else fetchSentimentTweets '', (r) -> toneRes makeBody r router.post '/', (req, res, next) -> if !req.body.text? or req.body.text == '' then noBodyProvided req, res, next else toneAnalyzer.tone req.body, (err, data) -> if err then next err else res.json data module.exports = router
105745
express = require('express') router = express.Router() fetchSentimentTweets = require '../utils/fetch-sentiment-tweets' watson = require 'watson-developer-cloud' watsonCredentials = require('../config/keys').watson toneAnalyzer = watson.tone_analyzer { url: 'https://gateway.watsonplatform.net/tone-analyzer/api' username: watsonCredentials.username password: <PASSWORD> version_date: '2016-11-02' version: 'v3' } noBodyProvided = (req, res, next) -> makeBody = (twAr) -> tweetBody = '' for tw in twAr then tweetBody += tw.body + ' ' tweetBody = tweetBody.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '') tweetBody = tweetBody.replace(/[^A-Za-z0-9 ]/g, '').substring(0, 5000) toneRes = (body) -> toneAnalyzer.tone {text: body}, (err, data) -> if err then next err else res.json data if req.body.searchTerm? && req.body.searchTerm != '' fetchSentimentTweets req.body.searchTerm, (r) -> toneRes makeBody r else fetchSentimentTweets '', (r) -> toneRes makeBody r router.post '/', (req, res, next) -> if !req.body.text? or req.body.text == '' then noBodyProvided req, res, next else toneAnalyzer.tone req.body, (err, data) -> if err then next err else res.json data module.exports = router
true
express = require('express') router = express.Router() fetchSentimentTweets = require '../utils/fetch-sentiment-tweets' watson = require 'watson-developer-cloud' watsonCredentials = require('../config/keys').watson toneAnalyzer = watson.tone_analyzer { url: 'https://gateway.watsonplatform.net/tone-analyzer/api' username: watsonCredentials.username password: PI:PASSWORD:<PASSWORD>END_PI version_date: '2016-11-02' version: 'v3' } noBodyProvided = (req, res, next) -> makeBody = (twAr) -> tweetBody = '' for tw in twAr then tweetBody += tw.body + ' ' tweetBody = tweetBody.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '') tweetBody = tweetBody.replace(/[^A-Za-z0-9 ]/g, '').substring(0, 5000) toneRes = (body) -> toneAnalyzer.tone {text: body}, (err, data) -> if err then next err else res.json data if req.body.searchTerm? && req.body.searchTerm != '' fetchSentimentTweets req.body.searchTerm, (r) -> toneRes makeBody r else fetchSentimentTweets '', (r) -> toneRes makeBody r router.post '/', (req, res, next) -> if !req.body.text? or req.body.text == '' then noBodyProvided req, res, next else toneAnalyzer.tone req.body, (err, data) -> if err then next err else res.json data module.exports = router
[ { "context": "sOfQuantumNeutrinoFields\n professor: \"Professor Hubert Farnsworth\"\n books: [\":shrug:\"]\n\n drop: ->\n con", "end": 297, "score": 0.9998828768730164, "start": 280, "tag": "NAME", "value": "Hubert Farnsworth" }, { "context": "ports.InlineClass = class InternalName\n name: \"Phillip J. Fry\"\n\nexports.Reexport = require(\"./simple-module\")\n", "end": 616, "score": 0.9998572468757629, "start": 602, "tag": "NAME", "value": "Phillip J. Fry" } ]
test/resources/exports/exports.coffee
hulu/splitshot
13
exports.Foo = "Some string" exports.Bar = { someObjectLiteral: true } exports.function = "fnucotin" # tests reserved word exports exports.getStuff = (anArgument) -> return ["stuff", "and more stuff"] class TheMathematicsOfQuantumNeutrinoFields professor: "Professor Hubert Farnsworth" books: [":shrug:"] drop: -> console.log("Good riddence") @register: -> console.log("Good luck") exports.MQNF = TheMathematicsOfQuantumNeutrinoFields exports.ClassInSession = new TheMathematicsOfQuantumNeutrinoFields() exports.InlineClass = class InternalName name: "Phillip J. Fry" exports.Reexport = require("./simple-module")
178131
exports.Foo = "Some string" exports.Bar = { someObjectLiteral: true } exports.function = "fnucotin" # tests reserved word exports exports.getStuff = (anArgument) -> return ["stuff", "and more stuff"] class TheMathematicsOfQuantumNeutrinoFields professor: "Professor <NAME>" books: [":shrug:"] drop: -> console.log("Good riddence") @register: -> console.log("Good luck") exports.MQNF = TheMathematicsOfQuantumNeutrinoFields exports.ClassInSession = new TheMathematicsOfQuantumNeutrinoFields() exports.InlineClass = class InternalName name: "<NAME>" exports.Reexport = require("./simple-module")
true
exports.Foo = "Some string" exports.Bar = { someObjectLiteral: true } exports.function = "fnucotin" # tests reserved word exports exports.getStuff = (anArgument) -> return ["stuff", "and more stuff"] class TheMathematicsOfQuantumNeutrinoFields professor: "Professor PI:NAME:<NAME>END_PI" books: [":shrug:"] drop: -> console.log("Good riddence") @register: -> console.log("Good luck") exports.MQNF = TheMathematicsOfQuantumNeutrinoFields exports.ClassInSession = new TheMathematicsOfQuantumNeutrinoFields() exports.InlineClass = class InternalName name: "PI:NAME:<NAME>END_PI" exports.Reexport = require("./simple-module")
[ { "context": "vent usage of this.state within setState\n# @author Rolf Erik Lekang, Jørgen Aaberg\n###\n\n'use strict'\n\ndocsUrl = requi", "end": 91, "score": 0.9998639822006226, "start": 75, "tag": "NAME", "value": "Rolf Erik Lekang" }, { "context": ".state within setState\n# @author Rolf Erik Lekang, Jørgen Aaberg\n###\n\n'use strict'\n\ndocsUrl = require 'eslint-plug", "end": 106, "score": 0.9998615384101868, "start": 93, "tag": "NAME", "value": "Jørgen Aaberg" } ]
src/rules/no-access-state-in-setstate.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Prevent usage of this.state within setState # @author Rolf Erik Lekang, Jørgen Aaberg ### 'use strict' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' {isDeclarationAssignment} = require '../util/ast-utils' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Reports when this.state is accessed within setState' category: 'Possible Errors' recommended: no url: docsUrl 'no-access-state-in-setstate' create: (context) -> isSetStateCall = (node) -> node.type is 'CallExpression' and node.callee.property and node.callee.property.name is 'setState' and node.callee.object.type is 'ThisExpression' isFirstArgumentInSetStateCall = (current, node) -> return no unless isSetStateCall current while node and node.parent isnt current then node = node.parent current.arguments[0] is node # The methods array contains all methods or functions that are using this.state # or that are calling another method or function using this.state methods = [] # The vars array contains all variables that contains this.state vars = [] CallExpression: (node) -> # Appends all the methods that are calling another # method containing this.state to the methods array methods.map (method) -> if node.callee.name is method.methodName current = node.parent while current.type isnt 'Program' if current.type is 'MethodDefinition' methods.push methodName: current.key.name node: method.node break current = current.parent # Finding all CallExpressions that is inside a setState # to further check if they contains this.state current = node.parent while current.type isnt 'Program' if isFirstArgumentInSetStateCall current, node methodName = node.callee.name for method in methods if method.methodName is methodName context.report( method.node 'Use callback in setState when referencing the previous state.' ) break current = current.parent MemberExpression: (node) -> if node.property.name is 'state' and node.object.type is 'ThisExpression' current = node prev = null while current.type isnt 'Program' # Reporting if this.state is directly within this.setState if isFirstArgumentInSetStateCall current, node context.report( node 'Use callback in setState when referencing the previous state.' ) break # Storing all functions and methods that contains this.state if current.type is 'MethodDefinition' methods.push { methodName: current.key.name node } break else if current.type is 'FunctionExpression' and current.parent.key methods.push { methodName: current.parent.key.name node } break # Storing all variables containg this.state if current.type is 'VariableDeclarator' vars.push { node scope: context.getScope() variableName: current.id.name } break if ( isDeclarationAssignment(current) and current.left.type is 'Identifier' and current.right is prev ) vars.push { node scope: context.getScope() variableName: current.left.name } break prev = current current = current.parent Identifier: (node) -> # Checks if the identifier is a variable within an object current = node while current.parent.type is 'BinaryExpression' current = current.parent if current.parent.value is current or current.parent.object is current while current.type isnt 'Program' if isFirstArgumentInSetStateCall current, node vars .filter (v) -> v.scope is context.getScope() and v.variableName is node.name .map (v) -> context.report( v.node 'Use callback in setState when referencing the previous state.' ) current = current.parent ObjectPattern: (node) -> isDerivedFromThis = (node.parent.init and node.parent.init.type is 'ThisExpression') or (isDeclarationAssignment(node.parent) and node.parent.right.type is 'ThisExpression') node.properties.forEach (property) -> if property?.key and property.key.name is 'state' and isDerivedFromThis vars.push node: property.key scope: context.getScope() variableName: property.key.name
115465
###* # @fileoverview Prevent usage of this.state within setState # @author <NAME>, <NAME> ### 'use strict' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' {isDeclarationAssignment} = require '../util/ast-utils' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Reports when this.state is accessed within setState' category: 'Possible Errors' recommended: no url: docsUrl 'no-access-state-in-setstate' create: (context) -> isSetStateCall = (node) -> node.type is 'CallExpression' and node.callee.property and node.callee.property.name is 'setState' and node.callee.object.type is 'ThisExpression' isFirstArgumentInSetStateCall = (current, node) -> return no unless isSetStateCall current while node and node.parent isnt current then node = node.parent current.arguments[0] is node # The methods array contains all methods or functions that are using this.state # or that are calling another method or function using this.state methods = [] # The vars array contains all variables that contains this.state vars = [] CallExpression: (node) -> # Appends all the methods that are calling another # method containing this.state to the methods array methods.map (method) -> if node.callee.name is method.methodName current = node.parent while current.type isnt 'Program' if current.type is 'MethodDefinition' methods.push methodName: current.key.name node: method.node break current = current.parent # Finding all CallExpressions that is inside a setState # to further check if they contains this.state current = node.parent while current.type isnt 'Program' if isFirstArgumentInSetStateCall current, node methodName = node.callee.name for method in methods if method.methodName is methodName context.report( method.node 'Use callback in setState when referencing the previous state.' ) break current = current.parent MemberExpression: (node) -> if node.property.name is 'state' and node.object.type is 'ThisExpression' current = node prev = null while current.type isnt 'Program' # Reporting if this.state is directly within this.setState if isFirstArgumentInSetStateCall current, node context.report( node 'Use callback in setState when referencing the previous state.' ) break # Storing all functions and methods that contains this.state if current.type is 'MethodDefinition' methods.push { methodName: current.key.name node } break else if current.type is 'FunctionExpression' and current.parent.key methods.push { methodName: current.parent.key.name node } break # Storing all variables containg this.state if current.type is 'VariableDeclarator' vars.push { node scope: context.getScope() variableName: current.id.name } break if ( isDeclarationAssignment(current) and current.left.type is 'Identifier' and current.right is prev ) vars.push { node scope: context.getScope() variableName: current.left.name } break prev = current current = current.parent Identifier: (node) -> # Checks if the identifier is a variable within an object current = node while current.parent.type is 'BinaryExpression' current = current.parent if current.parent.value is current or current.parent.object is current while current.type isnt 'Program' if isFirstArgumentInSetStateCall current, node vars .filter (v) -> v.scope is context.getScope() and v.variableName is node.name .map (v) -> context.report( v.node 'Use callback in setState when referencing the previous state.' ) current = current.parent ObjectPattern: (node) -> isDerivedFromThis = (node.parent.init and node.parent.init.type is 'ThisExpression') or (isDeclarationAssignment(node.parent) and node.parent.right.type is 'ThisExpression') node.properties.forEach (property) -> if property?.key and property.key.name is 'state' and isDerivedFromThis vars.push node: property.key scope: context.getScope() variableName: property.key.name
true
###* # @fileoverview Prevent usage of this.state within setState # @author PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ### 'use strict' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' {isDeclarationAssignment} = require '../util/ast-utils' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Reports when this.state is accessed within setState' category: 'Possible Errors' recommended: no url: docsUrl 'no-access-state-in-setstate' create: (context) -> isSetStateCall = (node) -> node.type is 'CallExpression' and node.callee.property and node.callee.property.name is 'setState' and node.callee.object.type is 'ThisExpression' isFirstArgumentInSetStateCall = (current, node) -> return no unless isSetStateCall current while node and node.parent isnt current then node = node.parent current.arguments[0] is node # The methods array contains all methods or functions that are using this.state # or that are calling another method or function using this.state methods = [] # The vars array contains all variables that contains this.state vars = [] CallExpression: (node) -> # Appends all the methods that are calling another # method containing this.state to the methods array methods.map (method) -> if node.callee.name is method.methodName current = node.parent while current.type isnt 'Program' if current.type is 'MethodDefinition' methods.push methodName: current.key.name node: method.node break current = current.parent # Finding all CallExpressions that is inside a setState # to further check if they contains this.state current = node.parent while current.type isnt 'Program' if isFirstArgumentInSetStateCall current, node methodName = node.callee.name for method in methods if method.methodName is methodName context.report( method.node 'Use callback in setState when referencing the previous state.' ) break current = current.parent MemberExpression: (node) -> if node.property.name is 'state' and node.object.type is 'ThisExpression' current = node prev = null while current.type isnt 'Program' # Reporting if this.state is directly within this.setState if isFirstArgumentInSetStateCall current, node context.report( node 'Use callback in setState when referencing the previous state.' ) break # Storing all functions and methods that contains this.state if current.type is 'MethodDefinition' methods.push { methodName: current.key.name node } break else if current.type is 'FunctionExpression' and current.parent.key methods.push { methodName: current.parent.key.name node } break # Storing all variables containg this.state if current.type is 'VariableDeclarator' vars.push { node scope: context.getScope() variableName: current.id.name } break if ( isDeclarationAssignment(current) and current.left.type is 'Identifier' and current.right is prev ) vars.push { node scope: context.getScope() variableName: current.left.name } break prev = current current = current.parent Identifier: (node) -> # Checks if the identifier is a variable within an object current = node while current.parent.type is 'BinaryExpression' current = current.parent if current.parent.value is current or current.parent.object is current while current.type isnt 'Program' if isFirstArgumentInSetStateCall current, node vars .filter (v) -> v.scope is context.getScope() and v.variableName is node.name .map (v) -> context.report( v.node 'Use callback in setState when referencing the previous state.' ) current = current.parent ObjectPattern: (node) -> isDerivedFromThis = (node.parent.init and node.parent.init.type is 'ThisExpression') or (isDeclarationAssignment(node.parent) and node.parent.right.type is 'ThisExpression') node.properties.forEach (property) -> if property?.key and property.key.name is 'state' and isDerivedFromThis vars.push node: property.key scope: context.getScope() variableName: property.key.name
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998855590820312, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespin", "end": 52, "score": 0.9999317526817322, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.9998788833618164, "start": 75, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bame", "end": 114, "score": 0.99993497133255, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998828172683716, "start": 137, "tag": "NAME", "value": "David Barragán Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.9999352693557739, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/modules/base/conf.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/conf.coffee ### defaults = { api: "http://localhost:8000/api/v1/" debug: true lang: "en" } class ConfigurationService @.$inject = ["localconf"] constructor: (localconf) -> @.config = _.merge(_.clone(defaults, true), localconf) get: (key, defaultValue=null) -> if _.has(@.config, key) return @.config[key] return defaultValue module = angular.module("taigaBase") module.service("$tgConfig", ConfigurationService) module.value("localconf", null)
54879
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/conf.coffee ### defaults = { api: "http://localhost:8000/api/v1/" debug: true lang: "en" } class ConfigurationService @.$inject = ["localconf"] constructor: (localconf) -> @.config = _.merge(_.clone(defaults, true), localconf) get: (key, defaultValue=null) -> if _.has(@.config, key) return @.config[key] return defaultValue module = angular.module("taigaBase") module.service("$tgConfig", ConfigurationService) module.value("localconf", null)
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/conf.coffee ### defaults = { api: "http://localhost:8000/api/v1/" debug: true lang: "en" } class ConfigurationService @.$inject = ["localconf"] constructor: (localconf) -> @.config = _.merge(_.clone(defaults, true), localconf) get: (key, defaultValue=null) -> if _.has(@.config, key) return @.config[key] return defaultValue module = angular.module("taigaBase") module.service("$tgConfig", ConfigurationService) module.value("localconf", null)
[ { "context": "ogin and logout', ->\n token = null\n username = 'test2'\n email = 'test2@ivus.com'\n password = 'passwor", "end": 324, "score": 0.9994690418243408, "start": 319, "tag": "USERNAME", "value": "test2" }, { "context": "->\n token = null\n username = 'test2'\n email = 'test2@ivus.com'\n password = 'password'\n\n # Delete the test acc", "end": 351, "score": 0.999928891658783, "start": 337, "tag": "EMAIL", "value": "test2@ivus.com" }, { "context": " 'test2'\n email = 'test2@ivus.com'\n password = 'password'\n\n # Delete the test account if it's still prese", "end": 375, "score": 0.9986647367477417, "start": 367, "tag": "PASSWORD", "value": "password" }, { "context": "me\n\n userId = Accounts.createUser {\n username: username\n email: email\n password: password\n }\n\n de", "end": 525, "score": 0.9974082112312317, "start": 517, "tag": "USERNAME", "value": "username" }, { "context": " username: username\n email: email\n password: password\n }\n\n describe 'with hook returns', ->\n it 's", "end": 565, "score": 0.9991803169250488, "start": 557, "tag": "PASSWORD", "value": "password" }, { "context": "k-api/login'), {\n data:\n username: username\n password: password\n }, waitFor (er", "end": 820, "score": 0.9952256679534912, "start": 812, "tag": "USERNAME", "value": "username" }, { "context": ":\n username: username\n password: password\n }, waitFor (error, result) ->\n respo", "end": 849, "score": 0.9983657002449036, "start": 841, "tag": "PASSWORD", "value": "password" }, { "context": "k-api/login'), {\n data:\n username: username\n password: password\n }, waitFor (er", "end": 1894, "score": 0.9968695044517517, "start": 1886, "tag": "USERNAME", "value": "username" }, { "context": ":\n username: username\n password: password\n }, waitFor (error, result) ->\n respo", "end": 1923, "score": 0.9992345571517944, "start": 1915, "tag": "PASSWORD", "value": "password" } ]
test/user_hook_tests.coffee
adthrasher/meteor-restivus
613
HookApi = new Restivus useDefaultAuth: true apiPath: 'hook-api' onLoggedIn: -> Meteor.users.findOne({_id: @userId}) onLoggedOut: -> Meteor.users.findOne({_id: @userId}) DefaultApi = new Restivus useDefaultAuth: true apiPath: 'no-hook-api' describe 'User login and logout', -> token = null username = 'test2' email = 'test2@ivus.com' password = 'password' # Delete the test account if it's still present Meteor.users.remove username: username userId = Accounts.createUser { username: username email: email password: password } describe 'with hook returns', -> it 'should call the onLoggedIn hook and attach returned data to the response as data.extra', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('hook-api/login'), { data: username: username password: password }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.userId, userId test.equal response.data.extra.username, username # Store the token for later use token = response.data.authToken it 'should call the onLoggedOut hook and attach returned data to the response as data.extra', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('hook-api/logout'), { headers: 'X-User-Id': userId 'X-Auth-Token': token }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.extra.username, username describe 'without hook returns', -> it 'should not attach data.extra to the response when login is called', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('no-hook-api/login'), { data: username: username password: password }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.userId, userId test.isUndefined response.data.extra # Store the token for later use token = response.data.authToken it 'should not attach data.extra to the response when logout is called', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('no-hook-api/logout'), { headers: 'X-User-Id': userId 'X-Auth-Token': token }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.isUndefined response.data.extra
101338
HookApi = new Restivus useDefaultAuth: true apiPath: 'hook-api' onLoggedIn: -> Meteor.users.findOne({_id: @userId}) onLoggedOut: -> Meteor.users.findOne({_id: @userId}) DefaultApi = new Restivus useDefaultAuth: true apiPath: 'no-hook-api' describe 'User login and logout', -> token = null username = 'test2' email = '<EMAIL>' password = '<PASSWORD>' # Delete the test account if it's still present Meteor.users.remove username: username userId = Accounts.createUser { username: username email: email password: <PASSWORD> } describe 'with hook returns', -> it 'should call the onLoggedIn hook and attach returned data to the response as data.extra', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('hook-api/login'), { data: username: username password: <PASSWORD> }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.userId, userId test.equal response.data.extra.username, username # Store the token for later use token = response.data.authToken it 'should call the onLoggedOut hook and attach returned data to the response as data.extra', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('hook-api/logout'), { headers: 'X-User-Id': userId 'X-Auth-Token': token }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.extra.username, username describe 'without hook returns', -> it 'should not attach data.extra to the response when login is called', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('no-hook-api/login'), { data: username: username password: <PASSWORD> }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.userId, userId test.isUndefined response.data.extra # Store the token for later use token = response.data.authToken it 'should not attach data.extra to the response when logout is called', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('no-hook-api/logout'), { headers: 'X-User-Id': userId 'X-Auth-Token': token }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.isUndefined response.data.extra
true
HookApi = new Restivus useDefaultAuth: true apiPath: 'hook-api' onLoggedIn: -> Meteor.users.findOne({_id: @userId}) onLoggedOut: -> Meteor.users.findOne({_id: @userId}) DefaultApi = new Restivus useDefaultAuth: true apiPath: 'no-hook-api' describe 'User login and logout', -> token = null username = 'test2' email = 'PI:EMAIL:<EMAIL>END_PI' password = 'PI:PASSWORD:<PASSWORD>END_PI' # Delete the test account if it's still present Meteor.users.remove username: username userId = Accounts.createUser { username: username email: email password: PI:PASSWORD:<PASSWORD>END_PI } describe 'with hook returns', -> it 'should call the onLoggedIn hook and attach returned data to the response as data.extra', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('hook-api/login'), { data: username: username password: PI:PASSWORD:<PASSWORD>END_PI }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.userId, userId test.equal response.data.extra.username, username # Store the token for later use token = response.data.authToken it 'should call the onLoggedOut hook and attach returned data to the response as data.extra', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('hook-api/logout'), { headers: 'X-User-Id': userId 'X-Auth-Token': token }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.extra.username, username describe 'without hook returns', -> it 'should not attach data.extra to the response when login is called', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('no-hook-api/login'), { data: username: username password: PI:PASSWORD:<PASSWORD>END_PI }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data.userId, userId test.isUndefined response.data.extra # Store the token for later use token = response.data.authToken it 'should not attach data.extra to the response when logout is called', (test, waitFor) -> HTTP.post Meteor.absoluteUrl('no-hook-api/logout'), { headers: 'X-User-Id': userId 'X-Auth-Token': token }, waitFor (error, result) -> response = result.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.isUndefined response.data.extra
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999109506607056, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/modding-profile/header.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Badges } from '../profile-page/badges' import { Detail } from './detail' import { HeaderInfo } from '../profile-page/header-info' import { Links } from '../profile-page/links' import { Stats } from './stats' import * as React from 'react' import HeaderV4 from 'header-v4' import { Img2x } from 'img2x' import { a, div, h1, li, span, ul } from 'react-dom-factories' el = React.createElement export class Header extends React.Component render: => div className: 'js-switchable-mode-page--scrollspy js-switchable-mode-page--page' 'data-page-id': 'main' el HeaderV4, backgroundImage: @props.user.cover_url contentPrepend: @renderTournamentBanner() links: @headerLinks() theme: 'users' div className: 'osu-page osu-page--users', div className: 'profile-header', div className: 'profile-header__top', el HeaderInfo, user: @props.user, currentMode: @props.user.playmode, coverUrl: @props.user.cover_url if !@props.user.is_bot el Stats, user: @props.user if !@props.user.is_bot el Detail, stats: @props.stats userAchievements: @props.userAchievements user: @props.user if @props.user.badges.length > 0 el Badges, badges: @props.user.badges el Links, user: @props.user renderTournamentBanner: ({modifiers} = {}) => return if !@props.user.active_tournament_banner.id? a href: laroute.route('tournaments.show', tournament: @props.user.active_tournament_banner.tournament_id) className: osu.classWithModifiers 'profile-tournament-banner', modifiers el Img2x, src: @props.user.active_tournament_banner.image className: 'profile-tournament-banner__image' headerLinks: => [ { url: laroute.route('users.show', user: @props.user.id) title: osu.trans 'layout.header.users.show' } { active: true title: osu.trans 'layout.header.users.modding' url: laroute.route('users.modding.index', user: @props.user.id) } ]
13907
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Badges } from '../profile-page/badges' import { Detail } from './detail' import { HeaderInfo } from '../profile-page/header-info' import { Links } from '../profile-page/links' import { Stats } from './stats' import * as React from 'react' import HeaderV4 from 'header-v4' import { Img2x } from 'img2x' import { a, div, h1, li, span, ul } from 'react-dom-factories' el = React.createElement export class Header extends React.Component render: => div className: 'js-switchable-mode-page--scrollspy js-switchable-mode-page--page' 'data-page-id': 'main' el HeaderV4, backgroundImage: @props.user.cover_url contentPrepend: @renderTournamentBanner() links: @headerLinks() theme: 'users' div className: 'osu-page osu-page--users', div className: 'profile-header', div className: 'profile-header__top', el HeaderInfo, user: @props.user, currentMode: @props.user.playmode, coverUrl: @props.user.cover_url if !@props.user.is_bot el Stats, user: @props.user if !@props.user.is_bot el Detail, stats: @props.stats userAchievements: @props.userAchievements user: @props.user if @props.user.badges.length > 0 el Badges, badges: @props.user.badges el Links, user: @props.user renderTournamentBanner: ({modifiers} = {}) => return if !@props.user.active_tournament_banner.id? a href: laroute.route('tournaments.show', tournament: @props.user.active_tournament_banner.tournament_id) className: osu.classWithModifiers 'profile-tournament-banner', modifiers el Img2x, src: @props.user.active_tournament_banner.image className: 'profile-tournament-banner__image' headerLinks: => [ { url: laroute.route('users.show', user: @props.user.id) title: osu.trans 'layout.header.users.show' } { active: true title: osu.trans 'layout.header.users.modding' url: laroute.route('users.modding.index', user: @props.user.id) } ]
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Badges } from '../profile-page/badges' import { Detail } from './detail' import { HeaderInfo } from '../profile-page/header-info' import { Links } from '../profile-page/links' import { Stats } from './stats' import * as React from 'react' import HeaderV4 from 'header-v4' import { Img2x } from 'img2x' import { a, div, h1, li, span, ul } from 'react-dom-factories' el = React.createElement export class Header extends React.Component render: => div className: 'js-switchable-mode-page--scrollspy js-switchable-mode-page--page' 'data-page-id': 'main' el HeaderV4, backgroundImage: @props.user.cover_url contentPrepend: @renderTournamentBanner() links: @headerLinks() theme: 'users' div className: 'osu-page osu-page--users', div className: 'profile-header', div className: 'profile-header__top', el HeaderInfo, user: @props.user, currentMode: @props.user.playmode, coverUrl: @props.user.cover_url if !@props.user.is_bot el Stats, user: @props.user if !@props.user.is_bot el Detail, stats: @props.stats userAchievements: @props.userAchievements user: @props.user if @props.user.badges.length > 0 el Badges, badges: @props.user.badges el Links, user: @props.user renderTournamentBanner: ({modifiers} = {}) => return if !@props.user.active_tournament_banner.id? a href: laroute.route('tournaments.show', tournament: @props.user.active_tournament_banner.tournament_id) className: osu.classWithModifiers 'profile-tournament-banner', modifiers el Img2x, src: @props.user.active_tournament_banner.image className: 'profile-tournament-banner__image' headerLinks: => [ { url: laroute.route('users.show', user: @props.user.id) title: osu.trans 'layout.header.users.show' } { active: true title: osu.trans 'layout.header.users.modding' url: laroute.route('users.modding.index', user: @props.user.id) } ]
[ { "context": ".mail.service\n user: config.mail.username\n pass: config.mail.password\n authMethod: \"LOGIN\"\n", "end": 622, "score": 0.9990832209587097, "start": 602, "tag": "PASSWORD", "value": "config.mail.password" } ]
server/commons/mail.coffee
madawei2699/codecombat
0
config = require '../../server_config' module.exports.MAILCHIMP_LIST_ID = 'e9851239eb' module.exports.MAILCHIMP_GROUP_ID = '4529' # these two need to be parallel module.exports.MAILCHIMP_GROUPS = ['Announcements', 'Adventurers', 'Artisans', 'Archmages', 'Scribes', 'Diplomats', 'Ambassadors'] module.exports.NEWS_GROUPS = ['generalNews', 'adventurerNews', 'artisanNews', 'archmageNews', 'scribeNews', 'diplomatNews', 'ambassadorNews'] nodemailer = require 'nodemailer' module.exports.transport = nodemailer.createTransport "SMTP", service: config.mail.service user: config.mail.username pass: config.mail.password authMethod: "LOGIN"
199593
config = require '../../server_config' module.exports.MAILCHIMP_LIST_ID = 'e9851239eb' module.exports.MAILCHIMP_GROUP_ID = '4529' # these two need to be parallel module.exports.MAILCHIMP_GROUPS = ['Announcements', 'Adventurers', 'Artisans', 'Archmages', 'Scribes', 'Diplomats', 'Ambassadors'] module.exports.NEWS_GROUPS = ['generalNews', 'adventurerNews', 'artisanNews', 'archmageNews', 'scribeNews', 'diplomatNews', 'ambassadorNews'] nodemailer = require 'nodemailer' module.exports.transport = nodemailer.createTransport "SMTP", service: config.mail.service user: config.mail.username pass: <PASSWORD> authMethod: "LOGIN"
true
config = require '../../server_config' module.exports.MAILCHIMP_LIST_ID = 'e9851239eb' module.exports.MAILCHIMP_GROUP_ID = '4529' # these two need to be parallel module.exports.MAILCHIMP_GROUPS = ['Announcements', 'Adventurers', 'Artisans', 'Archmages', 'Scribes', 'Diplomats', 'Ambassadors'] module.exports.NEWS_GROUPS = ['generalNews', 'adventurerNews', 'artisanNews', 'archmageNews', 'scribeNews', 'diplomatNews', 'ambassadorNews'] nodemailer = require 'nodemailer' module.exports.transport = nodemailer.createTransport "SMTP", service: config.mail.service user: config.mail.username pass: PI:PASSWORD:<PASSWORD>END_PI authMethod: "LOGIN"
[ { "context": " File : bigbang.coffee\n# Maintainer : Felix C. Stegerman <flx@obfusk.net>\n# Date : 2020-09-02\n#", "end": 97, "score": 0.9998835921287537, "start": 79, "tag": "NAME", "value": "Felix C. Stegerman" }, { "context": "ng.coffee\n# Maintainer : Felix C. Stegerman <flx@obfusk.net>\n# Date : 2020-09-02\n#\n# Copyright", "end": 113, "score": 0.9999352693557739, "start": 99, "tag": "EMAIL", "value": "flx@obfusk.net" }, { "context": "20-09-02\n#\n# Copyright : Copyright (C) 2020 Felix C. Stegerman\n# Licence : LGPLv3+\n# Version : v", "end": 206, "score": 0.9998798966407776, "start": 188, "tag": "NAME", "value": "Felix C. Stegerman" } ]
src/bigbang.coffee
obfusk/bigbang.coffee
1
# <!-- ### # {{{1 --> # # File : bigbang.coffee # Maintainer : Felix C. Stegerman <flx@obfusk.net> # Date : 2020-09-02 # # Copyright : Copyright (C) 2020 Felix C. Stegerman # Licence : LGPLv3+ # Version : v0.2.1 # # <!-- }}}1 ### # --> # graphical/evented functional programming for js/coffee # # Create graphical and evented programs (like games) in coffeescript # or javascript using plain mathematical functions; inspired by the # 2htdp library for racket. # # https://github.com/obfusk/bigbang.coffee # # License: LGPLv3+. # underscore + exports # -------------------- U = this._ || require 'underscore' B = -> B.bigbang arguments... if exports? then module.exports = B else this.bigbang = B # requestAnimationFrame & polyfill # -------------------------------- # requestAnimationFrame polyfill; the default delay is 17 milliseconds # (ca. 60 fps) B.polyRequestAnimationFrame = polyRequestAnimationFrame = # {{{1 (opts = {}) -> console.warn 'polyfilling *RequestAnimationFrame ...' if opts.warn delay = opts.delay || 17; next = 0 (cb) -> cur = +new Date dt = Math.max 0, delay - (cur - next) next = cur + dt window.setTimeout (-> cb +new Date), dt # <!-- }}}1 --> # NB: we use the prefixed versions of requestAnimationFrame b/c # requestAnimationFrame itself uses relative timestamps; also good to # know: webkitRequestAnimationFrame uses floating point timestamps. B.requestAnimationFrame = requestAnimationFrame = window?.requestAnimationFrame || window?.webkitRequestAnimationFrame || window?.mozRequestAnimationFrame || polyRequestAnimationFrame warn: true # bigbang & stop_with # ------------------- # <!-- {{{1 --> # # big bang: start a new universe whose behaviour is specified by the # options and handler functions designated # # bigbang # world: object, # canvas: element|object, # to_draw: ((world) -> scene), # on_tick: ((world, time) -> new_world), # fps: int, # queue: boolean|int, # animate: requestAnimationFrame-like-function, # on_key: ((world, key) -> new_world), # on_click: ((world, x, y) -> new_world), # on: { foo: ((world, ...) -> new_world), ... }, # stop_when: ((world) -> boolean), # last_draw: ((world) -> scene), # setup: ((canvas, handlers) -> setup_value), # teardown: ((canvas, handlers, setup_value) -> # teardown_value), # on_stop: ((world, teardown_value) -> ...) # -> {get_world,get_done} # # Options: # # * `world` is the object representing the initial world # * `canvas` is the HTML5 canvas (or equivalent) to draw on # * `to_draw` is called every time a new world needs to be drawn # # * (optional) `on_tick` # - when passed, the universe is in "clock mode": all changes are # queued (unless `queue` is `false`) and drawing happens every # actual clock tick (usually approx. 60 fps); `on_tick` is called # every "virtual" clock tick (as determined by `fps`) # - otherwise, events are processed immediately (by updating the # world and re-drawing the scene) # * (optional) `fps` is the requested frame rate; defaults to 60 # * (optional) `queue` when set to `false`, disables queueing in # "clock mode"; when set to an `int`, restricts the queue size to # that number of items (e.g. to draw every actual tick and ignore # all but the last world, set this to `1`) # * (optional) `animate` the requestAnimationFrame-like function to # use as the clock in "clock mode" # * (optional) `on_key` is called every time a key is pressed to # update the world # * (optional) `on_click` is called every time the mouse is clicked # inside the canvas to update the world # * (optional) `on` contains handlers for user-defined events; # `setup` and `teardown` are used to connect handlers to elements # and events; when the user-defined event is triggered, the # appropriate function is called # * (optional) `stop_when` is called to determine if the universe # needs to stop # * (optional) `last_draw` is called instead of `to_draw` to draw # the last world # * (optional) `setup` is called before the universe starts; the # handlers are the internal event handlers for `on` which `setup` # is expected to connect to the appropriate elements and events # * (optional) `teardown` is called after the universe has ended, # before on_stop; the handlers are the same as passed to `setup` # and can be used to cancel the event handling # * (optional) `on_stop` is called after the universe has ended, # after teardown # # Returns: # # * `get_world` is a function that returns the current world # * `get_done` is a function that returns whether the universe is # stopped # # <!-- ... --> # # The canvas need not be an actual canvas: it can be any element you # wish to "draw" the world with. It can be (part of) the body of an # event-driven page. In this case, you will also have a different # concept of "scene". For more on "scenes", see `mk_scene`. # # To stop the world from `on_tick` etc., return `stop_with(new_world)` # instead of `new_world`. # # For details on key press handling, see `handle_keys`. If you want # to use a different key press handling library, set the `handle_keys` # option to a function with the same api as `handle_keys`. # # For details on mouse click handling, see `handle_click`. # # <!-- }}}1 --> B.bigbang = (opts) -> # {{{1 tickless = !opts.on_tick queue = opts.queue ? true anim = opts.animate || requestAnimationFrame world = opts.world delay = 1000 / (opts.fps || 60) delay_margin = delay / 17 # ??? done = opts.stop_when?(world) || false next = +new Date + delay changes = [] setup_value = null if tickless && (opts.queue? || opts.fps || opts.animate) throw new Error 'queue, fps and animate require on_tick' draw = (w,d) -> f = if d && opts.last_draw then opts.last_draw else opts.to_draw draw_scene(f w) opts.canvas draw_changes = -> for {world:w,done:d} in changes draw w, d changes = [] change = (f, args...) -> return if done || !U.isFunction f x = f world, args... if x instanceof _Stop world = x.world done = true else world = x done = true if opts.stop_when? world if !tickless && queue changes.shift() if changes.length == queue # != true is OK changes.push {world,done} else draw world, done finish() if done s = +new Date tick = (t) -> if t >= next - delay_margin next += delay; change opts.on_tick, t draw_changes() if queue if done finish() if queue else anim tick key = (k) -> change opts.on_key, k click = (x,y) -> change opts.on_click, x, y handlers = {} for k, v of opts.on || {} do (k,v) -> handlers[k] = (args...) -> change v, args... finish = -> cancel_keys?(); cancel_click?() tv = opts.teardown? opts.canvas, handlers, setup_value opts.on_stop? world, tv hk = opts.handle_keys || handle_keys hc = opts.handle_click || handle_click cancel_keys = opts.on_key && hk opts.canvas, key , opts.$ cancel_click = opts.on_click && hc opts.canvas, click, opts.$ setup_value = opts.setup? opts.canvas, handlers draw world, done anim tick unless tickless world: (-> world), done: (-> done) # <!-- }}}1 --> # stop the universe; see bigbang B.stop_with = stop_with = (w) -> new _Stop w # wrapper class for stop_with class _Stop constructor: (@world) -> B._Stop = _Stop # abstract scene functions # ------------------------ # make a scene # # A "scene" is a function that takes a "canvas" and "draws" on it. # # A "non-recursive scene" is a "scene" that also takes a second # argument specifying whether any "lower scene" should also be drawn # by it and has a property `lower_scene` that holds the "lower scene". # This allows `draw_scene` to draw multiple scenes using iteration # instead of recursion. # # `mk_scene` takes a "non-recursive (lower) scene" and a "regular # scene" and turns the "regular scene" into a "non-recursive scene" # that draws the "lower scene" when needed. B.mk_scene = mk_scene = (scene, f) -> g = (canvas, draw_lower = true) -> scene? canvas if draw_lower; f canvas g.lower_scene = scene; g # draw a scene B.draw_scene = draw_scene = (scene) -> (canvas) -> if (s = scene).lower_scene scenes = [scene]; scenes.push s while s = s.lower_scene scenes.reverse(); s canvas, false for s in scenes; null else scene canvas # HTML5 canvas scene functions # ---------------------------- # empty scene B.empty_scene = empty_scene = (width, height) -> mk_scene null, (canvas) -> canvas.width = width; canvas.height = height # text with center at coordinates B.place_text = place_text = # {{{1 (string, x, y, fontsize, colour, scene, $ = window.$) -> \ mk_scene scene, (canvas) -> ctx = canvas.getContext '2d' ctx.save() ctx.font = "#{fontsize} sans-serif" ctx.fillStyle = colour ctx.textBaseline = 'bottom' {w,h} = measure_text $, string, fontsize, 'sans-serif' ctx.fillText string, Math.round(x - w / 2), Math.round(y + h / 2) ctx.restore() # <!-- }}}1 --> # image with center at coordinates B.place_image = place_image = (image, x, y, scene) -> mk_scene scene, (canvas) -> ctx = canvas.getContext '2d' x_ = x - Math.round(image.width / 2) y_ = y - Math.round(image.height / 2) ctx.drawImage image, x_, y_ # ... TODO: more scene and image functions ... # keyboard functions # ------------------ # <!-- {{{1 --> # # Handle key presses. Listens to keydown on elem, calls f with the # key_to_string'd key; returns a function that cancels the listening. # the key presses handled are a-z, 0-9, and the keys in keycodes (with # the exception of SHIFT); with and without shift; when alt, ctrl, or # meta is pressed, the key press is ignored. # # Why only this limited set of key presses you ask? Because of # browser and keyboard layout inconsistencies. For example, a German # keyboard layout will result in incorrect results with chromium, and # even less correct results with firefox. The key presses currently # handled seem to be the ones that work correctly in both firefox and # chromium, for both US English and German keyboard layouts. YMMV. # # <!-- }}}1 --> B.handle_keys = handle_keys = (elem, f, $ = window.$) -> # {{{1 h = (e) -> if !e.altKey && !e.ctrlKey && !e.metaKey && e.which != keycodes.SHIFT k = key_to_string e.which, e.shiftKey; f k if k k == null else true $(elem).on 'keydown', h -> $(elem).off 'keydown', h # <!-- }}}1 --> # Turn keypress into something usable: a-z without shift is returned # as "a"-"z"; A-Z with shift is returned as "A"-"Z"; 0-9 without shift # is returned as "0"-"9"; 0-9 with shift is returned as # "SHIFT_0".."SHIFT_9"; the other key codes are retured as the keys in # keycodes, lowercase when without shift (e.g. "left"), uppercase when # with shift (e.g. "HOME"). B.key_to_string = key_to_string = (which, shift) -> # {{{1 w = which; s = shift switch when keyranges.ALPHA.from <= w <= keyranges.ALPHA.to c = String.fromCharCode w if s then c else c.toLowerCase() when keyranges.NUM.from <= w <= keyranges.NUM.to c = String.fromCharCode w if s then "SHIFT_#{c}" else c else for k, v of keycodes if v == w return if s then k else k.toLowerCase() null # <!-- }}}1 --> # key codes B.keycodes = keycodes = BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 # key ranges B.keyranges = keyranges = ALPHA: { from: 65, to: 90 }, NUM: { from: 48, to: 57 }, # ... # mouse functions # --------------- # Handle mouse clicks. Listens to click on elem, calls f with the # {x,y}; returns a function that cancels the listening. B.handle_click = handle_click = (elem, f, $ = window.$) -> h = (e) -> {x,y} = mouse_position e; f x, y; false $(elem).on 'click', h -> $(elem).off 'click', h # relative mouse position; returns {x,y} B.mouse_position = mouse_position = (event, elem = event.target, $ = window.$, cache = {}) -> e = $(elem) cache.left ?= (e.outerWidth() - e.width() ) / 2 cache.top ?= (e.outerHeight() - e.height()) / 2 x: event.offsetX - cache.left, y: event.offsetY - cache.top # miscellaneous functions # ----------------------- # measure text height and width using a temporary hidden div; # returns {w:width,h:height} B.measure_text = measure_text = ($, text, size, family) -> # {{{1 c = measure_text.cache["#{size}|#{family}|#{text}"] return c if c d = $ '<div>'; d.text text d.css display: 'none', 'font-size': size, 'font-family': family $('body').append d w = d.width(); h = d.height() d.remove() measure_text.cache["#{size}|#{family}|#{text}"] = {w,h} measure_text.cache = {} # <!-- }}}1 --> # <!-- vim: set tw=70 sw=2 sts=2 et fdm=marker : -->
41042
# <!-- ### # {{{1 --> # # File : bigbang.coffee # Maintainer : <NAME> <<EMAIL>> # Date : 2020-09-02 # # Copyright : Copyright (C) 2020 <NAME> # Licence : LGPLv3+ # Version : v0.2.1 # # <!-- }}}1 ### # --> # graphical/evented functional programming for js/coffee # # Create graphical and evented programs (like games) in coffeescript # or javascript using plain mathematical functions; inspired by the # 2htdp library for racket. # # https://github.com/obfusk/bigbang.coffee # # License: LGPLv3+. # underscore + exports # -------------------- U = this._ || require 'underscore' B = -> B.bigbang arguments... if exports? then module.exports = B else this.bigbang = B # requestAnimationFrame & polyfill # -------------------------------- # requestAnimationFrame polyfill; the default delay is 17 milliseconds # (ca. 60 fps) B.polyRequestAnimationFrame = polyRequestAnimationFrame = # {{{1 (opts = {}) -> console.warn 'polyfilling *RequestAnimationFrame ...' if opts.warn delay = opts.delay || 17; next = 0 (cb) -> cur = +new Date dt = Math.max 0, delay - (cur - next) next = cur + dt window.setTimeout (-> cb +new Date), dt # <!-- }}}1 --> # NB: we use the prefixed versions of requestAnimationFrame b/c # requestAnimationFrame itself uses relative timestamps; also good to # know: webkitRequestAnimationFrame uses floating point timestamps. B.requestAnimationFrame = requestAnimationFrame = window?.requestAnimationFrame || window?.webkitRequestAnimationFrame || window?.mozRequestAnimationFrame || polyRequestAnimationFrame warn: true # bigbang & stop_with # ------------------- # <!-- {{{1 --> # # big bang: start a new universe whose behaviour is specified by the # options and handler functions designated # # bigbang # world: object, # canvas: element|object, # to_draw: ((world) -> scene), # on_tick: ((world, time) -> new_world), # fps: int, # queue: boolean|int, # animate: requestAnimationFrame-like-function, # on_key: ((world, key) -> new_world), # on_click: ((world, x, y) -> new_world), # on: { foo: ((world, ...) -> new_world), ... }, # stop_when: ((world) -> boolean), # last_draw: ((world) -> scene), # setup: ((canvas, handlers) -> setup_value), # teardown: ((canvas, handlers, setup_value) -> # teardown_value), # on_stop: ((world, teardown_value) -> ...) # -> {get_world,get_done} # # Options: # # * `world` is the object representing the initial world # * `canvas` is the HTML5 canvas (or equivalent) to draw on # * `to_draw` is called every time a new world needs to be drawn # # * (optional) `on_tick` # - when passed, the universe is in "clock mode": all changes are # queued (unless `queue` is `false`) and drawing happens every # actual clock tick (usually approx. 60 fps); `on_tick` is called # every "virtual" clock tick (as determined by `fps`) # - otherwise, events are processed immediately (by updating the # world and re-drawing the scene) # * (optional) `fps` is the requested frame rate; defaults to 60 # * (optional) `queue` when set to `false`, disables queueing in # "clock mode"; when set to an `int`, restricts the queue size to # that number of items (e.g. to draw every actual tick and ignore # all but the last world, set this to `1`) # * (optional) `animate` the requestAnimationFrame-like function to # use as the clock in "clock mode" # * (optional) `on_key` is called every time a key is pressed to # update the world # * (optional) `on_click` is called every time the mouse is clicked # inside the canvas to update the world # * (optional) `on` contains handlers for user-defined events; # `setup` and `teardown` are used to connect handlers to elements # and events; when the user-defined event is triggered, the # appropriate function is called # * (optional) `stop_when` is called to determine if the universe # needs to stop # * (optional) `last_draw` is called instead of `to_draw` to draw # the last world # * (optional) `setup` is called before the universe starts; the # handlers are the internal event handlers for `on` which `setup` # is expected to connect to the appropriate elements and events # * (optional) `teardown` is called after the universe has ended, # before on_stop; the handlers are the same as passed to `setup` # and can be used to cancel the event handling # * (optional) `on_stop` is called after the universe has ended, # after teardown # # Returns: # # * `get_world` is a function that returns the current world # * `get_done` is a function that returns whether the universe is # stopped # # <!-- ... --> # # The canvas need not be an actual canvas: it can be any element you # wish to "draw" the world with. It can be (part of) the body of an # event-driven page. In this case, you will also have a different # concept of "scene". For more on "scenes", see `mk_scene`. # # To stop the world from `on_tick` etc., return `stop_with(new_world)` # instead of `new_world`. # # For details on key press handling, see `handle_keys`. If you want # to use a different key press handling library, set the `handle_keys` # option to a function with the same api as `handle_keys`. # # For details on mouse click handling, see `handle_click`. # # <!-- }}}1 --> B.bigbang = (opts) -> # {{{1 tickless = !opts.on_tick queue = opts.queue ? true anim = opts.animate || requestAnimationFrame world = opts.world delay = 1000 / (opts.fps || 60) delay_margin = delay / 17 # ??? done = opts.stop_when?(world) || false next = +new Date + delay changes = [] setup_value = null if tickless && (opts.queue? || opts.fps || opts.animate) throw new Error 'queue, fps and animate require on_tick' draw = (w,d) -> f = if d && opts.last_draw then opts.last_draw else opts.to_draw draw_scene(f w) opts.canvas draw_changes = -> for {world:w,done:d} in changes draw w, d changes = [] change = (f, args...) -> return if done || !U.isFunction f x = f world, args... if x instanceof _Stop world = x.world done = true else world = x done = true if opts.stop_when? world if !tickless && queue changes.shift() if changes.length == queue # != true is OK changes.push {world,done} else draw world, done finish() if done s = +new Date tick = (t) -> if t >= next - delay_margin next += delay; change opts.on_tick, t draw_changes() if queue if done finish() if queue else anim tick key = (k) -> change opts.on_key, k click = (x,y) -> change opts.on_click, x, y handlers = {} for k, v of opts.on || {} do (k,v) -> handlers[k] = (args...) -> change v, args... finish = -> cancel_keys?(); cancel_click?() tv = opts.teardown? opts.canvas, handlers, setup_value opts.on_stop? world, tv hk = opts.handle_keys || handle_keys hc = opts.handle_click || handle_click cancel_keys = opts.on_key && hk opts.canvas, key , opts.$ cancel_click = opts.on_click && hc opts.canvas, click, opts.$ setup_value = opts.setup? opts.canvas, handlers draw world, done anim tick unless tickless world: (-> world), done: (-> done) # <!-- }}}1 --> # stop the universe; see bigbang B.stop_with = stop_with = (w) -> new _Stop w # wrapper class for stop_with class _Stop constructor: (@world) -> B._Stop = _Stop # abstract scene functions # ------------------------ # make a scene # # A "scene" is a function that takes a "canvas" and "draws" on it. # # A "non-recursive scene" is a "scene" that also takes a second # argument specifying whether any "lower scene" should also be drawn # by it and has a property `lower_scene` that holds the "lower scene". # This allows `draw_scene` to draw multiple scenes using iteration # instead of recursion. # # `mk_scene` takes a "non-recursive (lower) scene" and a "regular # scene" and turns the "regular scene" into a "non-recursive scene" # that draws the "lower scene" when needed. B.mk_scene = mk_scene = (scene, f) -> g = (canvas, draw_lower = true) -> scene? canvas if draw_lower; f canvas g.lower_scene = scene; g # draw a scene B.draw_scene = draw_scene = (scene) -> (canvas) -> if (s = scene).lower_scene scenes = [scene]; scenes.push s while s = s.lower_scene scenes.reverse(); s canvas, false for s in scenes; null else scene canvas # HTML5 canvas scene functions # ---------------------------- # empty scene B.empty_scene = empty_scene = (width, height) -> mk_scene null, (canvas) -> canvas.width = width; canvas.height = height # text with center at coordinates B.place_text = place_text = # {{{1 (string, x, y, fontsize, colour, scene, $ = window.$) -> \ mk_scene scene, (canvas) -> ctx = canvas.getContext '2d' ctx.save() ctx.font = "#{fontsize} sans-serif" ctx.fillStyle = colour ctx.textBaseline = 'bottom' {w,h} = measure_text $, string, fontsize, 'sans-serif' ctx.fillText string, Math.round(x - w / 2), Math.round(y + h / 2) ctx.restore() # <!-- }}}1 --> # image with center at coordinates B.place_image = place_image = (image, x, y, scene) -> mk_scene scene, (canvas) -> ctx = canvas.getContext '2d' x_ = x - Math.round(image.width / 2) y_ = y - Math.round(image.height / 2) ctx.drawImage image, x_, y_ # ... TODO: more scene and image functions ... # keyboard functions # ------------------ # <!-- {{{1 --> # # Handle key presses. Listens to keydown on elem, calls f with the # key_to_string'd key; returns a function that cancels the listening. # the key presses handled are a-z, 0-9, and the keys in keycodes (with # the exception of SHIFT); with and without shift; when alt, ctrl, or # meta is pressed, the key press is ignored. # # Why only this limited set of key presses you ask? Because of # browser and keyboard layout inconsistencies. For example, a German # keyboard layout will result in incorrect results with chromium, and # even less correct results with firefox. The key presses currently # handled seem to be the ones that work correctly in both firefox and # chromium, for both US English and German keyboard layouts. YMMV. # # <!-- }}}1 --> B.handle_keys = handle_keys = (elem, f, $ = window.$) -> # {{{1 h = (e) -> if !e.altKey && !e.ctrlKey && !e.metaKey && e.which != keycodes.SHIFT k = key_to_string e.which, e.shiftKey; f k if k k == null else true $(elem).on 'keydown', h -> $(elem).off 'keydown', h # <!-- }}}1 --> # Turn keypress into something usable: a-z without shift is returned # as "a"-"z"; A-Z with shift is returned as "A"-"Z"; 0-9 without shift # is returned as "0"-"9"; 0-9 with shift is returned as # "SHIFT_0".."SHIFT_9"; the other key codes are retured as the keys in # keycodes, lowercase when without shift (e.g. "left"), uppercase when # with shift (e.g. "HOME"). B.key_to_string = key_to_string = (which, shift) -> # {{{1 w = which; s = shift switch when keyranges.ALPHA.from <= w <= keyranges.ALPHA.to c = String.fromCharCode w if s then c else c.toLowerCase() when keyranges.NUM.from <= w <= keyranges.NUM.to c = String.fromCharCode w if s then "SHIFT_#{c}" else c else for k, v of keycodes if v == w return if s then k else k.toLowerCase() null # <!-- }}}1 --> # key codes B.keycodes = keycodes = BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 # key ranges B.keyranges = keyranges = ALPHA: { from: 65, to: 90 }, NUM: { from: 48, to: 57 }, # ... # mouse functions # --------------- # Handle mouse clicks. Listens to click on elem, calls f with the # {x,y}; returns a function that cancels the listening. B.handle_click = handle_click = (elem, f, $ = window.$) -> h = (e) -> {x,y} = mouse_position e; f x, y; false $(elem).on 'click', h -> $(elem).off 'click', h # relative mouse position; returns {x,y} B.mouse_position = mouse_position = (event, elem = event.target, $ = window.$, cache = {}) -> e = $(elem) cache.left ?= (e.outerWidth() - e.width() ) / 2 cache.top ?= (e.outerHeight() - e.height()) / 2 x: event.offsetX - cache.left, y: event.offsetY - cache.top # miscellaneous functions # ----------------------- # measure text height and width using a temporary hidden div; # returns {w:width,h:height} B.measure_text = measure_text = ($, text, size, family) -> # {{{1 c = measure_text.cache["#{size}|#{family}|#{text}"] return c if c d = $ '<div>'; d.text text d.css display: 'none', 'font-size': size, 'font-family': family $('body').append d w = d.width(); h = d.height() d.remove() measure_text.cache["#{size}|#{family}|#{text}"] = {w,h} measure_text.cache = {} # <!-- }}}1 --> # <!-- vim: set tw=70 sw=2 sts=2 et fdm=marker : -->
true
# <!-- ### # {{{1 --> # # File : bigbang.coffee # Maintainer : PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Date : 2020-09-02 # # Copyright : Copyright (C) 2020 PI:NAME:<NAME>END_PI # Licence : LGPLv3+ # Version : v0.2.1 # # <!-- }}}1 ### # --> # graphical/evented functional programming for js/coffee # # Create graphical and evented programs (like games) in coffeescript # or javascript using plain mathematical functions; inspired by the # 2htdp library for racket. # # https://github.com/obfusk/bigbang.coffee # # License: LGPLv3+. # underscore + exports # -------------------- U = this._ || require 'underscore' B = -> B.bigbang arguments... if exports? then module.exports = B else this.bigbang = B # requestAnimationFrame & polyfill # -------------------------------- # requestAnimationFrame polyfill; the default delay is 17 milliseconds # (ca. 60 fps) B.polyRequestAnimationFrame = polyRequestAnimationFrame = # {{{1 (opts = {}) -> console.warn 'polyfilling *RequestAnimationFrame ...' if opts.warn delay = opts.delay || 17; next = 0 (cb) -> cur = +new Date dt = Math.max 0, delay - (cur - next) next = cur + dt window.setTimeout (-> cb +new Date), dt # <!-- }}}1 --> # NB: we use the prefixed versions of requestAnimationFrame b/c # requestAnimationFrame itself uses relative timestamps; also good to # know: webkitRequestAnimationFrame uses floating point timestamps. B.requestAnimationFrame = requestAnimationFrame = window?.requestAnimationFrame || window?.webkitRequestAnimationFrame || window?.mozRequestAnimationFrame || polyRequestAnimationFrame warn: true # bigbang & stop_with # ------------------- # <!-- {{{1 --> # # big bang: start a new universe whose behaviour is specified by the # options and handler functions designated # # bigbang # world: object, # canvas: element|object, # to_draw: ((world) -> scene), # on_tick: ((world, time) -> new_world), # fps: int, # queue: boolean|int, # animate: requestAnimationFrame-like-function, # on_key: ((world, key) -> new_world), # on_click: ((world, x, y) -> new_world), # on: { foo: ((world, ...) -> new_world), ... }, # stop_when: ((world) -> boolean), # last_draw: ((world) -> scene), # setup: ((canvas, handlers) -> setup_value), # teardown: ((canvas, handlers, setup_value) -> # teardown_value), # on_stop: ((world, teardown_value) -> ...) # -> {get_world,get_done} # # Options: # # * `world` is the object representing the initial world # * `canvas` is the HTML5 canvas (or equivalent) to draw on # * `to_draw` is called every time a new world needs to be drawn # # * (optional) `on_tick` # - when passed, the universe is in "clock mode": all changes are # queued (unless `queue` is `false`) and drawing happens every # actual clock tick (usually approx. 60 fps); `on_tick` is called # every "virtual" clock tick (as determined by `fps`) # - otherwise, events are processed immediately (by updating the # world and re-drawing the scene) # * (optional) `fps` is the requested frame rate; defaults to 60 # * (optional) `queue` when set to `false`, disables queueing in # "clock mode"; when set to an `int`, restricts the queue size to # that number of items (e.g. to draw every actual tick and ignore # all but the last world, set this to `1`) # * (optional) `animate` the requestAnimationFrame-like function to # use as the clock in "clock mode" # * (optional) `on_key` is called every time a key is pressed to # update the world # * (optional) `on_click` is called every time the mouse is clicked # inside the canvas to update the world # * (optional) `on` contains handlers for user-defined events; # `setup` and `teardown` are used to connect handlers to elements # and events; when the user-defined event is triggered, the # appropriate function is called # * (optional) `stop_when` is called to determine if the universe # needs to stop # * (optional) `last_draw` is called instead of `to_draw` to draw # the last world # * (optional) `setup` is called before the universe starts; the # handlers are the internal event handlers for `on` which `setup` # is expected to connect to the appropriate elements and events # * (optional) `teardown` is called after the universe has ended, # before on_stop; the handlers are the same as passed to `setup` # and can be used to cancel the event handling # * (optional) `on_stop` is called after the universe has ended, # after teardown # # Returns: # # * `get_world` is a function that returns the current world # * `get_done` is a function that returns whether the universe is # stopped # # <!-- ... --> # # The canvas need not be an actual canvas: it can be any element you # wish to "draw" the world with. It can be (part of) the body of an # event-driven page. In this case, you will also have a different # concept of "scene". For more on "scenes", see `mk_scene`. # # To stop the world from `on_tick` etc., return `stop_with(new_world)` # instead of `new_world`. # # For details on key press handling, see `handle_keys`. If you want # to use a different key press handling library, set the `handle_keys` # option to a function with the same api as `handle_keys`. # # For details on mouse click handling, see `handle_click`. # # <!-- }}}1 --> B.bigbang = (opts) -> # {{{1 tickless = !opts.on_tick queue = opts.queue ? true anim = opts.animate || requestAnimationFrame world = opts.world delay = 1000 / (opts.fps || 60) delay_margin = delay / 17 # ??? done = opts.stop_when?(world) || false next = +new Date + delay changes = [] setup_value = null if tickless && (opts.queue? || opts.fps || opts.animate) throw new Error 'queue, fps and animate require on_tick' draw = (w,d) -> f = if d && opts.last_draw then opts.last_draw else opts.to_draw draw_scene(f w) opts.canvas draw_changes = -> for {world:w,done:d} in changes draw w, d changes = [] change = (f, args...) -> return if done || !U.isFunction f x = f world, args... if x instanceof _Stop world = x.world done = true else world = x done = true if opts.stop_when? world if !tickless && queue changes.shift() if changes.length == queue # != true is OK changes.push {world,done} else draw world, done finish() if done s = +new Date tick = (t) -> if t >= next - delay_margin next += delay; change opts.on_tick, t draw_changes() if queue if done finish() if queue else anim tick key = (k) -> change opts.on_key, k click = (x,y) -> change opts.on_click, x, y handlers = {} for k, v of opts.on || {} do (k,v) -> handlers[k] = (args...) -> change v, args... finish = -> cancel_keys?(); cancel_click?() tv = opts.teardown? opts.canvas, handlers, setup_value opts.on_stop? world, tv hk = opts.handle_keys || handle_keys hc = opts.handle_click || handle_click cancel_keys = opts.on_key && hk opts.canvas, key , opts.$ cancel_click = opts.on_click && hc opts.canvas, click, opts.$ setup_value = opts.setup? opts.canvas, handlers draw world, done anim tick unless tickless world: (-> world), done: (-> done) # <!-- }}}1 --> # stop the universe; see bigbang B.stop_with = stop_with = (w) -> new _Stop w # wrapper class for stop_with class _Stop constructor: (@world) -> B._Stop = _Stop # abstract scene functions # ------------------------ # make a scene # # A "scene" is a function that takes a "canvas" and "draws" on it. # # A "non-recursive scene" is a "scene" that also takes a second # argument specifying whether any "lower scene" should also be drawn # by it and has a property `lower_scene` that holds the "lower scene". # This allows `draw_scene` to draw multiple scenes using iteration # instead of recursion. # # `mk_scene` takes a "non-recursive (lower) scene" and a "regular # scene" and turns the "regular scene" into a "non-recursive scene" # that draws the "lower scene" when needed. B.mk_scene = mk_scene = (scene, f) -> g = (canvas, draw_lower = true) -> scene? canvas if draw_lower; f canvas g.lower_scene = scene; g # draw a scene B.draw_scene = draw_scene = (scene) -> (canvas) -> if (s = scene).lower_scene scenes = [scene]; scenes.push s while s = s.lower_scene scenes.reverse(); s canvas, false for s in scenes; null else scene canvas # HTML5 canvas scene functions # ---------------------------- # empty scene B.empty_scene = empty_scene = (width, height) -> mk_scene null, (canvas) -> canvas.width = width; canvas.height = height # text with center at coordinates B.place_text = place_text = # {{{1 (string, x, y, fontsize, colour, scene, $ = window.$) -> \ mk_scene scene, (canvas) -> ctx = canvas.getContext '2d' ctx.save() ctx.font = "#{fontsize} sans-serif" ctx.fillStyle = colour ctx.textBaseline = 'bottom' {w,h} = measure_text $, string, fontsize, 'sans-serif' ctx.fillText string, Math.round(x - w / 2), Math.round(y + h / 2) ctx.restore() # <!-- }}}1 --> # image with center at coordinates B.place_image = place_image = (image, x, y, scene) -> mk_scene scene, (canvas) -> ctx = canvas.getContext '2d' x_ = x - Math.round(image.width / 2) y_ = y - Math.round(image.height / 2) ctx.drawImage image, x_, y_ # ... TODO: more scene and image functions ... # keyboard functions # ------------------ # <!-- {{{1 --> # # Handle key presses. Listens to keydown on elem, calls f with the # key_to_string'd key; returns a function that cancels the listening. # the key presses handled are a-z, 0-9, and the keys in keycodes (with # the exception of SHIFT); with and without shift; when alt, ctrl, or # meta is pressed, the key press is ignored. # # Why only this limited set of key presses you ask? Because of # browser and keyboard layout inconsistencies. For example, a German # keyboard layout will result in incorrect results with chromium, and # even less correct results with firefox. The key presses currently # handled seem to be the ones that work correctly in both firefox and # chromium, for both US English and German keyboard layouts. YMMV. # # <!-- }}}1 --> B.handle_keys = handle_keys = (elem, f, $ = window.$) -> # {{{1 h = (e) -> if !e.altKey && !e.ctrlKey && !e.metaKey && e.which != keycodes.SHIFT k = key_to_string e.which, e.shiftKey; f k if k k == null else true $(elem).on 'keydown', h -> $(elem).off 'keydown', h # <!-- }}}1 --> # Turn keypress into something usable: a-z without shift is returned # as "a"-"z"; A-Z with shift is returned as "A"-"Z"; 0-9 without shift # is returned as "0"-"9"; 0-9 with shift is returned as # "SHIFT_0".."SHIFT_9"; the other key codes are retured as the keys in # keycodes, lowercase when without shift (e.g. "left"), uppercase when # with shift (e.g. "HOME"). B.key_to_string = key_to_string = (which, shift) -> # {{{1 w = which; s = shift switch when keyranges.ALPHA.from <= w <= keyranges.ALPHA.to c = String.fromCharCode w if s then c else c.toLowerCase() when keyranges.NUM.from <= w <= keyranges.NUM.to c = String.fromCharCode w if s then "SHIFT_#{c}" else c else for k, v of keycodes if v == w return if s then k else k.toLowerCase() null # <!-- }}}1 --> # key codes B.keycodes = keycodes = BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 # key ranges B.keyranges = keyranges = ALPHA: { from: 65, to: 90 }, NUM: { from: 48, to: 57 }, # ... # mouse functions # --------------- # Handle mouse clicks. Listens to click on elem, calls f with the # {x,y}; returns a function that cancels the listening. B.handle_click = handle_click = (elem, f, $ = window.$) -> h = (e) -> {x,y} = mouse_position e; f x, y; false $(elem).on 'click', h -> $(elem).off 'click', h # relative mouse position; returns {x,y} B.mouse_position = mouse_position = (event, elem = event.target, $ = window.$, cache = {}) -> e = $(elem) cache.left ?= (e.outerWidth() - e.width() ) / 2 cache.top ?= (e.outerHeight() - e.height()) / 2 x: event.offsetX - cache.left, y: event.offsetY - cache.top # miscellaneous functions # ----------------------- # measure text height and width using a temporary hidden div; # returns {w:width,h:height} B.measure_text = measure_text = ($, text, size, family) -> # {{{1 c = measure_text.cache["#{size}|#{family}|#{text}"] return c if c d = $ '<div>'; d.text text d.css display: 'none', 'font-size': size, 'font-family': family $('body').append d w = d.width(); h = d.height() d.remove() measure_text.cache["#{size}|#{family}|#{text}"] = {w,h} measure_text.cache = {} # <!-- }}}1 --> # <!-- vim: set tw=70 sw=2 sts=2 et fdm=marker : -->
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999147653579712, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/status-chart.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @StatusChart constructor: (element, name) -> @ratio = 2 * Math.PI width = $(element).width() height = $(element).height() outerRadius = Math.min(width, height) / 2 innerRadius = outerRadius / 4.7 * 4 @defaultArc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) .startAngle(0) @svg = d3.select(element) .append('svg') .attr('width', '100%') .attr('height', '100%') .attr('viewBox', "0 0 #{Math.min(width, height)} #{Math.min(width, height)}") .attr('preserveAspectRatio', 'xMinYMin') .append('g') .attr('transform', "translate(#{Math.min(width, height) / 2}, #{Math.min(width, height) / 2})") @text = @svg.append('text') .text(name) .attr('dy', -8) .classed('status-chart__text', true) @percentage = @svg.append('text') .attr('dy', 20) .classed('status-chart__text status-chart__text--percentage', true) @background = @svg.append('path') .datum(endAngle: @ratio) .classed('status-chart__background', true) .attr('d', @defaultArc) @upArc = @svg.append('path') .datum(endAngle: 0) .classed('status-chart__up-arc', true) .attr('d', @defaultArc) @downArc = @svg.append('path') .datum(endAngle: 0) .classed('status-chart__down-arc', true) .attr('d', @defaultArc) parse: (n) -> @ratio * n / 100 set: (data) => arcTween = (transition, newAngle) => transition.attrTween 'd', (d) => interpolate = d3.interpolate(d.endAngle, newAngle) (t) => d.endAngle = interpolate(t) @percentage.text Math.round((d.endAngle / @ratio) * 100) + '%' @defaultArc d @downArc.transition().duration(750).call(arcTween, -@parse(data.down)) @upArc.transition().duration(750).call(arcTween, @parse(data.up))
204182
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @StatusChart constructor: (element, name) -> @ratio = 2 * Math.PI width = $(element).width() height = $(element).height() outerRadius = Math.min(width, height) / 2 innerRadius = outerRadius / 4.7 * 4 @defaultArc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) .startAngle(0) @svg = d3.select(element) .append('svg') .attr('width', '100%') .attr('height', '100%') .attr('viewBox', "0 0 #{Math.min(width, height)} #{Math.min(width, height)}") .attr('preserveAspectRatio', 'xMinYMin') .append('g') .attr('transform', "translate(#{Math.min(width, height) / 2}, #{Math.min(width, height) / 2})") @text = @svg.append('text') .text(name) .attr('dy', -8) .classed('status-chart__text', true) @percentage = @svg.append('text') .attr('dy', 20) .classed('status-chart__text status-chart__text--percentage', true) @background = @svg.append('path') .datum(endAngle: @ratio) .classed('status-chart__background', true) .attr('d', @defaultArc) @upArc = @svg.append('path') .datum(endAngle: 0) .classed('status-chart__up-arc', true) .attr('d', @defaultArc) @downArc = @svg.append('path') .datum(endAngle: 0) .classed('status-chart__down-arc', true) .attr('d', @defaultArc) parse: (n) -> @ratio * n / 100 set: (data) => arcTween = (transition, newAngle) => transition.attrTween 'd', (d) => interpolate = d3.interpolate(d.endAngle, newAngle) (t) => d.endAngle = interpolate(t) @percentage.text Math.round((d.endAngle / @ratio) * 100) + '%' @defaultArc d @downArc.transition().duration(750).call(arcTween, -@parse(data.down)) @upArc.transition().duration(750).call(arcTween, @parse(data.up))
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @StatusChart constructor: (element, name) -> @ratio = 2 * Math.PI width = $(element).width() height = $(element).height() outerRadius = Math.min(width, height) / 2 innerRadius = outerRadius / 4.7 * 4 @defaultArc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) .startAngle(0) @svg = d3.select(element) .append('svg') .attr('width', '100%') .attr('height', '100%') .attr('viewBox', "0 0 #{Math.min(width, height)} #{Math.min(width, height)}") .attr('preserveAspectRatio', 'xMinYMin') .append('g') .attr('transform', "translate(#{Math.min(width, height) / 2}, #{Math.min(width, height) / 2})") @text = @svg.append('text') .text(name) .attr('dy', -8) .classed('status-chart__text', true) @percentage = @svg.append('text') .attr('dy', 20) .classed('status-chart__text status-chart__text--percentage', true) @background = @svg.append('path') .datum(endAngle: @ratio) .classed('status-chart__background', true) .attr('d', @defaultArc) @upArc = @svg.append('path') .datum(endAngle: 0) .classed('status-chart__up-arc', true) .attr('d', @defaultArc) @downArc = @svg.append('path') .datum(endAngle: 0) .classed('status-chart__down-arc', true) .attr('d', @defaultArc) parse: (n) -> @ratio * n / 100 set: (data) => arcTween = (transition, newAngle) => transition.attrTween 'd', (d) => interpolate = d3.interpolate(d.endAngle, newAngle) (t) => d.endAngle = interpolate(t) @percentage.text Math.round((d.endAngle / @ratio) * 100) + '%' @defaultArc d @downArc.transition().duration(750).call(arcTween, -@parse(data.down)) @upArc.transition().duration(750).call(arcTween, @parse(data.up))
[ { "context": ">\n @sut = new GetGlobalPublicKey publicKey: 'oh, hi mom!'\n\n describe 'when called', ->\n beforeEach ", "end": 201, "score": 0.7798652648925781, "start": 189, "tag": "KEY", "value": "oh, hi mom!'" }, { "context": " expect(@response.data).to.deep.equal publicKey: 'oh, hi mom!'\n\n describe 'when instantiated without a public k", "end": 535, "score": 0.7692230343818665, "start": 523, "tag": "KEY", "value": "oh, hi mom!'" } ]
test/get-global-public-key-spec.coffee
octoblu/meshblu-core-task-get-global-public-key
0
GetGlobalPublicKey = require '../' describe 'GetGlobalPublicKey', -> describe 'when instantiated with a public key', -> beforeEach -> @sut = new GetGlobalPublicKey publicKey: 'oh, hi mom!' describe 'when called', -> beforeEach (done) -> @sut.do {}, (error, @response) => done error it 'should get have the status code of 200', -> expect(@response.metadata.code).to.equal 200 it 'should return the publicKey', -> expect(@response.data).to.deep.equal publicKey: 'oh, hi mom!' describe 'when instantiated without a public key', -> beforeEach -> @sut = new GetGlobalPublicKey publicKey: undefined describe 'when called', -> beforeEach (done) -> @sut.do {}, (error, @response) => done error it 'should get have the status code of 204', -> expect(@response.metadata.code).to.equal 204 it 'should return null', -> expect(@response.data).to.be.undefined
59376
GetGlobalPublicKey = require '../' describe 'GetGlobalPublicKey', -> describe 'when instantiated with a public key', -> beforeEach -> @sut = new GetGlobalPublicKey publicKey: '<KEY> describe 'when called', -> beforeEach (done) -> @sut.do {}, (error, @response) => done error it 'should get have the status code of 200', -> expect(@response.metadata.code).to.equal 200 it 'should return the publicKey', -> expect(@response.data).to.deep.equal publicKey: '<KEY> describe 'when instantiated without a public key', -> beforeEach -> @sut = new GetGlobalPublicKey publicKey: undefined describe 'when called', -> beforeEach (done) -> @sut.do {}, (error, @response) => done error it 'should get have the status code of 204', -> expect(@response.metadata.code).to.equal 204 it 'should return null', -> expect(@response.data).to.be.undefined
true
GetGlobalPublicKey = require '../' describe 'GetGlobalPublicKey', -> describe 'when instantiated with a public key', -> beforeEach -> @sut = new GetGlobalPublicKey publicKey: 'PI:KEY:<KEY>END_PI describe 'when called', -> beforeEach (done) -> @sut.do {}, (error, @response) => done error it 'should get have the status code of 200', -> expect(@response.metadata.code).to.equal 200 it 'should return the publicKey', -> expect(@response.data).to.deep.equal publicKey: 'PI:KEY:<KEY>END_PI describe 'when instantiated without a public key', -> beforeEach -> @sut = new GetGlobalPublicKey publicKey: undefined describe 'when called', -> beforeEach (done) -> @sut.do {}, (error, @response) => done error it 'should get have the status code of 204', -> expect(@response.metadata.code).to.equal 204 it 'should return null', -> expect(@response.data).to.be.undefined
[ { "context": "llipse\"\n\n# svg.import.js 0.11 - Copyright (c) 2013 Wout Fierens - Licensed under the MIT license\n#\n# Converted to", "end": 205, "score": 0.9998770952224731, "start": 193, "tag": "NAME", "value": "Wout Fierens" } ]
src/deserialize-svg.coffee
ocxtal/curve
53
SVG = require "../vendor/svg" require "../vendor/svg.parser" Path = require "./path" Rectangle = require "./rectangle" Ellipse = require "./ellipse" # svg.import.js 0.11 - Copyright (c) 2013 Wout Fierens - Licensed under the MIT license # # Converted to coffeescript and modified by benogle # Place the `svgString` in the svgDocument, and parse into objects Curve can # understand # # * `svgDocument` A {SVGDocument} # * `svgString` {String} with the svg markup # # Returns an array of objects selectable and editable by Curve tools. module.exports = (svgDocument, svgString) -> IMPORT_FNS = path: (el) -> [new Path(svgDocument, svgEl: el)] rect: (el) -> [new Rectangle(svgDocument, svgEl: el)] circle: (el) -> [new Ellipse(svgDocument, svgEl: el)] ellipse: (el) -> [new Ellipse(svgDocument, svgEl: el)] # create temporary div to receive svg content parentNode = document.createElement('div') store = {} # properly close svg tags and add them to the DOM parentNode.innerHTML = svgString .replace(/\n/, '') .replace(/<(\w+)([^<]+?)\/>/g, '<$1$2></$1>') objects = [] convertNodes parentNode.childNodes, svgDocument.getSVGRoot(), 0, store, -> nodeType = this.node.nodeName objects = objects.concat(IMPORT_FNS[nodeType](this)) if IMPORT_FNS[nodeType] null parentNode = null objects # Convert nodes to svg.js elements convertNodes = (nodes, context, level, store, block) -> for i in [0...nodes.length] element = null child = nodes[i] attr = {} clips = [] # get node type type = child.nodeName.toLowerCase() # objectify attributes attr = SVG.parse.attr(child) # create elements switch type when 'path' then element = context[type]() when 'polygon' then element = context[type]() when 'polyline' then element = context[type]() when 'rect' then element = context[type](0,0) when 'circle' then element = context[type](0,0) when 'ellipse' then element = context[type](0,0) when 'line' then element = context.line(0,0,0,0) when 'text' if child.childNodes.length == 0 element = context[type](child.textContent) else element = null for j in [0...child.childNodes.length] grandchild = child.childNodes[j] if grandchild.nodeName.toLowerCase() == 'tspan' if element == null # first time through call the text() function on the current context element = context[type](grandchild.textContent) else # for the remaining times create additional tspans element .tspan(grandchild.textContent) .attr(SVG.parse.attr(grandchild)) when 'image' then element = context.image(attr['xlink:href']) when 'g', 'svg' element = context[if type == 'g' then 'group' else 'nested']() convertNodes(child.childNodes, element, level + 1, store, block) when 'defs' convertNodes(child.childNodes, context.defs(), level + 1, store, block) when 'use' element = context.use() when 'clippath', 'mask' element = context[type == 'mask' ? 'mask' : 'clip']() convertNodes(child.childNodes, element, level + 1, store, block) when 'lineargradient', 'radialgradient' element = context.defs().gradient type.split('gradient')[0], (stop) -> for j in [0...child.childNodes.length] stop .at(offset: 0) .attr(SVG.parse.attr(child.childNodes[j])) .style(child.childNodes[j].getAttribute('style')) when '#comment', '#text', 'metadata', 'desc' ; # safely ignore these elements else console.log('SVG Import got unexpected type ' + type, child) if element # parse transform attribute transform = SVG.parse.transform(attr.transform) delete attr.transform # set attributes and transformations element .attr(attr) .transform(transform) # store element by id store[element.attr('id')] = element if element.attr('id') # now that we've set the attributes "rebuild" the text to correctly set the attributes element.rebuild() if type == 'text' # call block if given block.call(element) if typeof block == 'function' context
203255
SVG = require "../vendor/svg" require "../vendor/svg.parser" Path = require "./path" Rectangle = require "./rectangle" Ellipse = require "./ellipse" # svg.import.js 0.11 - Copyright (c) 2013 <NAME> - Licensed under the MIT license # # Converted to coffeescript and modified by benogle # Place the `svgString` in the svgDocument, and parse into objects Curve can # understand # # * `svgDocument` A {SVGDocument} # * `svgString` {String} with the svg markup # # Returns an array of objects selectable and editable by Curve tools. module.exports = (svgDocument, svgString) -> IMPORT_FNS = path: (el) -> [new Path(svgDocument, svgEl: el)] rect: (el) -> [new Rectangle(svgDocument, svgEl: el)] circle: (el) -> [new Ellipse(svgDocument, svgEl: el)] ellipse: (el) -> [new Ellipse(svgDocument, svgEl: el)] # create temporary div to receive svg content parentNode = document.createElement('div') store = {} # properly close svg tags and add them to the DOM parentNode.innerHTML = svgString .replace(/\n/, '') .replace(/<(\w+)([^<]+?)\/>/g, '<$1$2></$1>') objects = [] convertNodes parentNode.childNodes, svgDocument.getSVGRoot(), 0, store, -> nodeType = this.node.nodeName objects = objects.concat(IMPORT_FNS[nodeType](this)) if IMPORT_FNS[nodeType] null parentNode = null objects # Convert nodes to svg.js elements convertNodes = (nodes, context, level, store, block) -> for i in [0...nodes.length] element = null child = nodes[i] attr = {} clips = [] # get node type type = child.nodeName.toLowerCase() # objectify attributes attr = SVG.parse.attr(child) # create elements switch type when 'path' then element = context[type]() when 'polygon' then element = context[type]() when 'polyline' then element = context[type]() when 'rect' then element = context[type](0,0) when 'circle' then element = context[type](0,0) when 'ellipse' then element = context[type](0,0) when 'line' then element = context.line(0,0,0,0) when 'text' if child.childNodes.length == 0 element = context[type](child.textContent) else element = null for j in [0...child.childNodes.length] grandchild = child.childNodes[j] if grandchild.nodeName.toLowerCase() == 'tspan' if element == null # first time through call the text() function on the current context element = context[type](grandchild.textContent) else # for the remaining times create additional tspans element .tspan(grandchild.textContent) .attr(SVG.parse.attr(grandchild)) when 'image' then element = context.image(attr['xlink:href']) when 'g', 'svg' element = context[if type == 'g' then 'group' else 'nested']() convertNodes(child.childNodes, element, level + 1, store, block) when 'defs' convertNodes(child.childNodes, context.defs(), level + 1, store, block) when 'use' element = context.use() when 'clippath', 'mask' element = context[type == 'mask' ? 'mask' : 'clip']() convertNodes(child.childNodes, element, level + 1, store, block) when 'lineargradient', 'radialgradient' element = context.defs().gradient type.split('gradient')[0], (stop) -> for j in [0...child.childNodes.length] stop .at(offset: 0) .attr(SVG.parse.attr(child.childNodes[j])) .style(child.childNodes[j].getAttribute('style')) when '#comment', '#text', 'metadata', 'desc' ; # safely ignore these elements else console.log('SVG Import got unexpected type ' + type, child) if element # parse transform attribute transform = SVG.parse.transform(attr.transform) delete attr.transform # set attributes and transformations element .attr(attr) .transform(transform) # store element by id store[element.attr('id')] = element if element.attr('id') # now that we've set the attributes "rebuild" the text to correctly set the attributes element.rebuild() if type == 'text' # call block if given block.call(element) if typeof block == 'function' context
true
SVG = require "../vendor/svg" require "../vendor/svg.parser" Path = require "./path" Rectangle = require "./rectangle" Ellipse = require "./ellipse" # svg.import.js 0.11 - Copyright (c) 2013 PI:NAME:<NAME>END_PI - Licensed under the MIT license # # Converted to coffeescript and modified by benogle # Place the `svgString` in the svgDocument, and parse into objects Curve can # understand # # * `svgDocument` A {SVGDocument} # * `svgString` {String} with the svg markup # # Returns an array of objects selectable and editable by Curve tools. module.exports = (svgDocument, svgString) -> IMPORT_FNS = path: (el) -> [new Path(svgDocument, svgEl: el)] rect: (el) -> [new Rectangle(svgDocument, svgEl: el)] circle: (el) -> [new Ellipse(svgDocument, svgEl: el)] ellipse: (el) -> [new Ellipse(svgDocument, svgEl: el)] # create temporary div to receive svg content parentNode = document.createElement('div') store = {} # properly close svg tags and add them to the DOM parentNode.innerHTML = svgString .replace(/\n/, '') .replace(/<(\w+)([^<]+?)\/>/g, '<$1$2></$1>') objects = [] convertNodes parentNode.childNodes, svgDocument.getSVGRoot(), 0, store, -> nodeType = this.node.nodeName objects = objects.concat(IMPORT_FNS[nodeType](this)) if IMPORT_FNS[nodeType] null parentNode = null objects # Convert nodes to svg.js elements convertNodes = (nodes, context, level, store, block) -> for i in [0...nodes.length] element = null child = nodes[i] attr = {} clips = [] # get node type type = child.nodeName.toLowerCase() # objectify attributes attr = SVG.parse.attr(child) # create elements switch type when 'path' then element = context[type]() when 'polygon' then element = context[type]() when 'polyline' then element = context[type]() when 'rect' then element = context[type](0,0) when 'circle' then element = context[type](0,0) when 'ellipse' then element = context[type](0,0) when 'line' then element = context.line(0,0,0,0) when 'text' if child.childNodes.length == 0 element = context[type](child.textContent) else element = null for j in [0...child.childNodes.length] grandchild = child.childNodes[j] if grandchild.nodeName.toLowerCase() == 'tspan' if element == null # first time through call the text() function on the current context element = context[type](grandchild.textContent) else # for the remaining times create additional tspans element .tspan(grandchild.textContent) .attr(SVG.parse.attr(grandchild)) when 'image' then element = context.image(attr['xlink:href']) when 'g', 'svg' element = context[if type == 'g' then 'group' else 'nested']() convertNodes(child.childNodes, element, level + 1, store, block) when 'defs' convertNodes(child.childNodes, context.defs(), level + 1, store, block) when 'use' element = context.use() when 'clippath', 'mask' element = context[type == 'mask' ? 'mask' : 'clip']() convertNodes(child.childNodes, element, level + 1, store, block) when 'lineargradient', 'radialgradient' element = context.defs().gradient type.split('gradient')[0], (stop) -> for j in [0...child.childNodes.length] stop .at(offset: 0) .attr(SVG.parse.attr(child.childNodes[j])) .style(child.childNodes[j].getAttribute('style')) when '#comment', '#text', 'metadata', 'desc' ; # safely ignore these elements else console.log('SVG Import got unexpected type ' + type, child) if element # parse transform attribute transform = SVG.parse.transform(attr.transform) delete attr.transform # set attributes and transformations element .attr(attr) .transform(transform) # store element by id store[element.attr('id')] = element if element.attr('id') # now that we've set the attributes "rebuild" the text to correctly set the attributes element.rebuild() if type == 'text' # call block if given block.call(element) if typeof block == 'function' context
[ { "context": "./format-number'\nEasyTable = require 'easy-table'\nPeter = require './players/peter'\nAaron = require './pl", "end": 100, "score": 0.9577273726463318, "start": 95, "tag": "NAME", "value": "Peter" }, { "context": "= require 'easy-table'\nPeter = require './players/peter'\nAaron = require './players/aaron'\nPLAYERS = {\n ", "end": 127, "score": 0.9517666697502136, "start": 122, "tag": "NAME", "value": "peter" }, { "context": "re 'easy-table'\nPeter = require './players/peter'\nAaron = require './players/aaron'\nPLAYERS = {\n 'peter'", "end": 134, "score": 0.969221830368042, "start": 129, "tag": "NAME", "value": "Aaron" }, { "context": "uire './players/peter'\nAaron = require './players/aaron'\nPLAYERS = {\n 'peter': Peter,\n 'aaron': Aaron\n}", "end": 161, "score": 0.9616302847862244, "start": 156, "tag": "NAME", "value": "aaron" }, { "context": "\nAaron = require './players/aaron'\nPLAYERS = {\n 'peter': Peter,\n 'aaron': Aaron\n}\n\nclass GameRunner\n c", "end": 183, "score": 0.9880993366241455, "start": 178, "tag": "NAME", "value": "peter" }, { "context": "= require './players/aaron'\nPLAYERS = {\n 'peter': Peter,\n 'aaron': Aaron\n}\n\nclass GameRunner\n construct", "end": 191, "score": 0.9992074370384216, "start": 186, "tag": "NAME", "value": "Peter" }, { "context": "./players/aaron'\nPLAYERS = {\n 'peter': Peter,\n 'aaron': Aaron\n}\n\nclass GameRunner\n constructor: (@numb", "end": 201, "score": 0.9982482194900513, "start": 196, "tag": "NAME", "value": "aaron" }, { "context": "rs/aaron'\nPLAYERS = {\n 'peter': Peter,\n 'aaron': Aaron\n}\n\nclass GameRunner\n constructor: (@numberOfGame", "end": 209, "score": 0.9996272325515747, "start": 204, "tag": "NAME", "value": "Aaron" } ]
lib/game-runner.coffee
peterdemartini/betting-strategies
0
_ = require 'lodash' formatNumber = require './format-number' EasyTable = require 'easy-table' Peter = require './players/peter' Aaron = require './players/aaron' PLAYERS = { 'peter': Peter, 'aaron': Aaron } class GameRunner constructor: (@numberOfGames=20, @gameName) -> @results = [] newPerson: (Player) => @player = new Player(@gameName) runGame: (index) => @gamesPlayed++ @player.play() lastWinnings = @player.lastWinnings @numberWon++ if lastWinnings > 0 @numberLost++ if lastWinnings < 0 @betAmounts.push(@player.currentBet) if @numberOfGames == @gamesPlayed @totalWinnings = @player.winningsPot runPlayer: (Player, playerName) => @newPerson(Player) _.each @player.strategies, (strategy) => @reset() result = {} @player.setStrategy(strategy) _.times @numberOfGames, @runGame result["Player"] = playerName result["Strategy"] = strategy result["Minumum"] = @player.minumum result["Total Won"] = '$' + formatNumber(@totalWinnings) result["# Played"] = @gamesPlayed result["Won / Lost"] = "#{@numberWon}/#{@numberLost}" winningRatio = Math.round(@numberWon / @numberOfGames * 100) result["Ratio"] = "%#{winningRatio}" result["Highest Bet"] = formatNumber _.max(@betAmounts) @results.push result @newPerson(Player) run: => _.each PLAYERS, @runPlayer reset: => @betAmounts = [] @numberWon = 0 @numberLost = 0 @totalWinnings = 0 @gamesPlayed = 0 output: => console.log EasyTable.printArray(@results) module.exports = GameRunner
216231
_ = require 'lodash' formatNumber = require './format-number' EasyTable = require 'easy-table' <NAME> = require './players/<NAME>' <NAME> = require './players/<NAME>' PLAYERS = { '<NAME>': <NAME>, '<NAME>': <NAME> } class GameRunner constructor: (@numberOfGames=20, @gameName) -> @results = [] newPerson: (Player) => @player = new Player(@gameName) runGame: (index) => @gamesPlayed++ @player.play() lastWinnings = @player.lastWinnings @numberWon++ if lastWinnings > 0 @numberLost++ if lastWinnings < 0 @betAmounts.push(@player.currentBet) if @numberOfGames == @gamesPlayed @totalWinnings = @player.winningsPot runPlayer: (Player, playerName) => @newPerson(Player) _.each @player.strategies, (strategy) => @reset() result = {} @player.setStrategy(strategy) _.times @numberOfGames, @runGame result["Player"] = playerName result["Strategy"] = strategy result["Minumum"] = @player.minumum result["Total Won"] = '$' + formatNumber(@totalWinnings) result["# Played"] = @gamesPlayed result["Won / Lost"] = "#{@numberWon}/#{@numberLost}" winningRatio = Math.round(@numberWon / @numberOfGames * 100) result["Ratio"] = "%#{winningRatio}" result["Highest Bet"] = formatNumber _.max(@betAmounts) @results.push result @newPerson(Player) run: => _.each PLAYERS, @runPlayer reset: => @betAmounts = [] @numberWon = 0 @numberLost = 0 @totalWinnings = 0 @gamesPlayed = 0 output: => console.log EasyTable.printArray(@results) module.exports = GameRunner
true
_ = require 'lodash' formatNumber = require './format-number' EasyTable = require 'easy-table' PI:NAME:<NAME>END_PI = require './players/PI:NAME:<NAME>END_PI' PI:NAME:<NAME>END_PI = require './players/PI:NAME:<NAME>END_PI' PLAYERS = { 'PI:NAME:<NAME>END_PI': PI:NAME:<NAME>END_PI, 'PI:NAME:<NAME>END_PI': PI:NAME:<NAME>END_PI } class GameRunner constructor: (@numberOfGames=20, @gameName) -> @results = [] newPerson: (Player) => @player = new Player(@gameName) runGame: (index) => @gamesPlayed++ @player.play() lastWinnings = @player.lastWinnings @numberWon++ if lastWinnings > 0 @numberLost++ if lastWinnings < 0 @betAmounts.push(@player.currentBet) if @numberOfGames == @gamesPlayed @totalWinnings = @player.winningsPot runPlayer: (Player, playerName) => @newPerson(Player) _.each @player.strategies, (strategy) => @reset() result = {} @player.setStrategy(strategy) _.times @numberOfGames, @runGame result["Player"] = playerName result["Strategy"] = strategy result["Minumum"] = @player.minumum result["Total Won"] = '$' + formatNumber(@totalWinnings) result["# Played"] = @gamesPlayed result["Won / Lost"] = "#{@numberWon}/#{@numberLost}" winningRatio = Math.round(@numberWon / @numberOfGames * 100) result["Ratio"] = "%#{winningRatio}" result["Highest Bet"] = formatNumber _.max(@betAmounts) @results.push result @newPerson(Player) run: => _.each PLAYERS, @runPlayer reset: => @betAmounts = [] @numberWon = 0 @numberLost = 0 @totalWinnings = 0 @gamesPlayed = 0 output: => console.log EasyTable.printArray(@results) module.exports = GameRunner
[ { "context": "es.map (x) ->\n return {\n author: x.author.username\n from: x.source.branch.name\n to: x.dest", "end": 274, "score": 0.5018647313117981, "start": 266, "tag": "USERNAME", "value": "username" }, { "context": "ord\n\n buildAuth: () ->\n return {\n \"user\": @bitBucketUsername\n \"pass\": @bitBucketPassword\n \"sendImmed", "end": 779, "score": 0.8340643644332886, "start": 761, "tag": "USERNAME", "value": "@bitBucketUsername" }, { "context": "n {\n \"user\": @bitBucketUsername\n \"pass\": @bitBucketPassword\n \"sendImmediately\": true\n }\n\n _get: (url", "end": 812, "score": 0.9357668161392212, "start": 794, "tag": "PASSWORD", "value": "@bitBucketPassword" }, { "context": "ect error\n\n return deferred.promise\n\n # /maprtech/mapr.com-content/pullrequests\n getPullRequests: ", "end": 2252, "score": 0.5688071250915527, "start": 2247, "tag": "USERNAME", "value": "rtech" } ]
lib/util/bitbucket-manager.coffee
ExentriqLtd/Advanced-Web-Editor
0
API_URL = 'https://api.bitbucket.org/2.0/repositories/' request = require 'request' q = require 'q' log = require './logger' PAGE_SIZE = 50 transformResponse = (body) -> if !body return [] return body.values.map (x) -> return { author: x.author.username from: x.source.branch.name to: x.destination.branch.name title: x.title state: x.state close_source_branch: x.close_source_branch } transformBranchResponse = (body) -> if !body return [] return body.values.map (x) -> x.name class BitBucketManager constructor: (@bitBucketUsername, @bitBucketPassword) -> # log.debug "BitBucketManager::constructor", @bitBucketUsername, @bitBucketPassword buildAuth: () -> return { "user": @bitBucketUsername "pass": @bitBucketPassword "sendImmediately": true } _get: (url) -> deferred = q.defer() options = url: url auth: @buildAuth() json: true request.get options, (error, response, body) -> try log.debug "_get got", url, body if error deferred.reject "Error occurred, Resource #{url}" else if response && response.statusCode != 200 deferred.reject "HTTP error #{response.statusCode}, Resource #{url}" else deferred.resolve body catch e deferred.reject e return deferred.promise invokeTillHasNext: (url, transformFunction, otherParams) -> deferred = q.defer() location= "#{url}?#{if otherParams then otherParams else ''}&pagelen=#{PAGE_SIZE}" #First invocation to know how many items we have @_get(location) .then (body) => firstPage = transformFunction(body) if !body.next deferred.resolve firstPage else pages = Math.ceil(body.size / PAGE_SIZE) promises = [] promises.push(@_get(location + "&page=#{i}")) for i in [2 .. pages] q.all(promises).then (resultBodies) -> results = resultBodies.map (x) -> transformFunction(x) toMerge = firstPage.concat(results) deferred.resolve [].concat.apply([], toMerge) .fail (error) -> deferred.reject error return deferred.promise # /maprtech/mapr.com-content/pullrequests getPullRequests: (repoOwner, repoName) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/pullrequests" @invokeTillHasNext(url, transformResponse).then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise createPullRequest: (title, description, repoOwner, repoName, fromBranch, toBranch) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/pullrequests" options = url: url auth: @buildAuth() json: true body: title: title description: description source: branch: name: fromBranch repository: full_name: "#{repoOwner}/#{repoName}" destination: branch: name: toBranch close_source_branch: true log.debug "BitBucketManager::createPullRequest", options request.post options, (error, response, body) -> try log.debug "API returned:", body deferred.resolve body catch error deferred.reject error return deferred.promise getBranches: (repoOwner, repoName) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/refs/branches" @invokeTillHasNext(url, transformBranchResponse).then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise getUserBranches: (repoOwner, repoName, username) -> #q=name ~ "/$USERNAME/" deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/refs/branches" @invokeTillHasNext(url, transformBranchResponse, "q=name+~+%22%2F#{username}%2F%22").then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise getRepoSize: (repoOwner, repoName) -> # log.debug "BitBucketManager::getRepoSize", repoOwner, repoName deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}" options = url: url auth: @buildAuth() json: true request.get options, (error, response, body) -> log.debug options, error, response, body try log.debug "API returned:", body deferred.resolve body.size catch e deferred.reject e return deferred.promise module.exports = BitBucketManager
142270
API_URL = 'https://api.bitbucket.org/2.0/repositories/' request = require 'request' q = require 'q' log = require './logger' PAGE_SIZE = 50 transformResponse = (body) -> if !body return [] return body.values.map (x) -> return { author: x.author.username from: x.source.branch.name to: x.destination.branch.name title: x.title state: x.state close_source_branch: x.close_source_branch } transformBranchResponse = (body) -> if !body return [] return body.values.map (x) -> x.name class BitBucketManager constructor: (@bitBucketUsername, @bitBucketPassword) -> # log.debug "BitBucketManager::constructor", @bitBucketUsername, @bitBucketPassword buildAuth: () -> return { "user": @bitBucketUsername "pass": <PASSWORD> "sendImmediately": true } _get: (url) -> deferred = q.defer() options = url: url auth: @buildAuth() json: true request.get options, (error, response, body) -> try log.debug "_get got", url, body if error deferred.reject "Error occurred, Resource #{url}" else if response && response.statusCode != 200 deferred.reject "HTTP error #{response.statusCode}, Resource #{url}" else deferred.resolve body catch e deferred.reject e return deferred.promise invokeTillHasNext: (url, transformFunction, otherParams) -> deferred = q.defer() location= "#{url}?#{if otherParams then otherParams else ''}&pagelen=#{PAGE_SIZE}" #First invocation to know how many items we have @_get(location) .then (body) => firstPage = transformFunction(body) if !body.next deferred.resolve firstPage else pages = Math.ceil(body.size / PAGE_SIZE) promises = [] promises.push(@_get(location + "&page=#{i}")) for i in [2 .. pages] q.all(promises).then (resultBodies) -> results = resultBodies.map (x) -> transformFunction(x) toMerge = firstPage.concat(results) deferred.resolve [].concat.apply([], toMerge) .fail (error) -> deferred.reject error return deferred.promise # /maprtech/mapr.com-content/pullrequests getPullRequests: (repoOwner, repoName) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/pullrequests" @invokeTillHasNext(url, transformResponse).then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise createPullRequest: (title, description, repoOwner, repoName, fromBranch, toBranch) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/pullrequests" options = url: url auth: @buildAuth() json: true body: title: title description: description source: branch: name: fromBranch repository: full_name: "#{repoOwner}/#{repoName}" destination: branch: name: toBranch close_source_branch: true log.debug "BitBucketManager::createPullRequest", options request.post options, (error, response, body) -> try log.debug "API returned:", body deferred.resolve body catch error deferred.reject error return deferred.promise getBranches: (repoOwner, repoName) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/refs/branches" @invokeTillHasNext(url, transformBranchResponse).then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise getUserBranches: (repoOwner, repoName, username) -> #q=name ~ "/$USERNAME/" deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/refs/branches" @invokeTillHasNext(url, transformBranchResponse, "q=name+~+%22%2F#{username}%2F%22").then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise getRepoSize: (repoOwner, repoName) -> # log.debug "BitBucketManager::getRepoSize", repoOwner, repoName deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}" options = url: url auth: @buildAuth() json: true request.get options, (error, response, body) -> log.debug options, error, response, body try log.debug "API returned:", body deferred.resolve body.size catch e deferred.reject e return deferred.promise module.exports = BitBucketManager
true
API_URL = 'https://api.bitbucket.org/2.0/repositories/' request = require 'request' q = require 'q' log = require './logger' PAGE_SIZE = 50 transformResponse = (body) -> if !body return [] return body.values.map (x) -> return { author: x.author.username from: x.source.branch.name to: x.destination.branch.name title: x.title state: x.state close_source_branch: x.close_source_branch } transformBranchResponse = (body) -> if !body return [] return body.values.map (x) -> x.name class BitBucketManager constructor: (@bitBucketUsername, @bitBucketPassword) -> # log.debug "BitBucketManager::constructor", @bitBucketUsername, @bitBucketPassword buildAuth: () -> return { "user": @bitBucketUsername "pass": PI:PASSWORD:<PASSWORD>END_PI "sendImmediately": true } _get: (url) -> deferred = q.defer() options = url: url auth: @buildAuth() json: true request.get options, (error, response, body) -> try log.debug "_get got", url, body if error deferred.reject "Error occurred, Resource #{url}" else if response && response.statusCode != 200 deferred.reject "HTTP error #{response.statusCode}, Resource #{url}" else deferred.resolve body catch e deferred.reject e return deferred.promise invokeTillHasNext: (url, transformFunction, otherParams) -> deferred = q.defer() location= "#{url}?#{if otherParams then otherParams else ''}&pagelen=#{PAGE_SIZE}" #First invocation to know how many items we have @_get(location) .then (body) => firstPage = transformFunction(body) if !body.next deferred.resolve firstPage else pages = Math.ceil(body.size / PAGE_SIZE) promises = [] promises.push(@_get(location + "&page=#{i}")) for i in [2 .. pages] q.all(promises).then (resultBodies) -> results = resultBodies.map (x) -> transformFunction(x) toMerge = firstPage.concat(results) deferred.resolve [].concat.apply([], toMerge) .fail (error) -> deferred.reject error return deferred.promise # /maprtech/mapr.com-content/pullrequests getPullRequests: (repoOwner, repoName) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/pullrequests" @invokeTillHasNext(url, transformResponse).then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise createPullRequest: (title, description, repoOwner, repoName, fromBranch, toBranch) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/pullrequests" options = url: url auth: @buildAuth() json: true body: title: title description: description source: branch: name: fromBranch repository: full_name: "#{repoOwner}/#{repoName}" destination: branch: name: toBranch close_source_branch: true log.debug "BitBucketManager::createPullRequest", options request.post options, (error, response, body) -> try log.debug "API returned:", body deferred.resolve body catch error deferred.reject error return deferred.promise getBranches: (repoOwner, repoName) -> deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/refs/branches" @invokeTillHasNext(url, transformBranchResponse).then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise getUserBranches: (repoOwner, repoName, username) -> #q=name ~ "/$USERNAME/" deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}/refs/branches" @invokeTillHasNext(url, transformBranchResponse, "q=name+~+%22%2F#{username}%2F%22").then (result) -> deferred.resolve result .fail (error) -> deferred.reject error return deferred.promise getRepoSize: (repoOwner, repoName) -> # log.debug "BitBucketManager::getRepoSize", repoOwner, repoName deferred = q.defer() url = "#{API_URL}#{repoOwner}/#{repoName}" options = url: url auth: @buildAuth() json: true request.get options, (error, response, body) -> log.debug options, error, response, body try log.debug "API returned:", body deferred.resolve body.size catch e deferred.reject e return deferred.promise module.exports = BitBucketManager
[ { "context": "oProject', ->\n\n\t\tbeforeEach ->\n\t\t\t@targetEmail = \"user@example.com\"\n\t\t\t@req.params =\n\t\t\t\tProject_id: @project_id\n\t\t\t", "end": 3156, "score": 0.9999133944511414, "start": 3140, "tag": "EMAIL", "value": "user@example.com" }, { "context": ")\n\t\t\t@invite = {\n\t\t\t\t_id: ObjectId(),\n\t\t\t\ttoken: \"htnseuthaouse\",\n\t\t\t\tsendingUserId: @current_user_id,\n\t\t\t\tprojec", "end": 3517, "score": 0.9987139701843262, "start": 3504, "tag": "PASSWORD", "value": "htnseuthaouse" }, { "context": "(),\n\t\t\t\ttoken: \"htnseuthaouse\",\n\t\t\t\tsendingUserId: @current_user_id,\n\t\t\t\tprojectId: @targetEmail,\n\t\t\t\ttargetEmail: 'u", "end": 3555, "score": 0.7945699095726013, "start": 3539, "tag": "USERNAME", "value": "@current_user_id" }, { "context": "d,\n\t\t\t\tprojectId: @targetEmail,\n\t\t\t\ttargetEmail: 'user@example.com'\n\t\t\t\tcreatedAt: new Date(),\n\t\t\t}\n\t\t\t@LimitationsM", "end": 3620, "score": 0.9999130964279175, "start": 3604, "tag": "EMAIL", "value": "user@example.com" }, { "context": "nviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false\n\n\t\t\tit 'should ", "end": 6219, "score": 0.9954836964607239, "start": 6207, "tag": "USERNAME", "value": "@sendingUser" }, { "context": "nviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false\n\n\t\t\tit 'should ", "end": 7147, "score": 0.9806153178215027, "start": 7135, "tag": "USERNAME", "value": "@sendingUser" }, { "context": "\n\n\t\t\tbeforeEach ->\n\t\t\t\t@req.session.user = {_id: 'abc', email: 'me@example.com'}\n\t\t\t\t@req.body.email = ", "end": 10641, "score": 0.7760363817214966, "start": 10638, "tag": "USERNAME", "value": "abc" }, { "context": "h ->\n\t\t\t\t@req.session.user = {_id: 'abc', email: 'me@example.com'}\n\t\t\t\t@req.body.email = 'me@example.com'\n\t\t\t\t@Col", "end": 10666, "score": 0.9999212026596069, "start": 10652, "tag": "EMAIL", "value": "me@example.com" }, { "context": ", email: 'me@example.com'}\n\t\t\t\t@req.body.email = 'me@example.com'\n\t\t\t\t@CollaboratorsInviteController._checkShouldI", "end": 10706, "score": 0.9999221563339233, "start": 10692, "tag": "EMAIL", "value": "me@example.com" }, { "context": "be \"viewInvite\", ->\n\n\t\tbeforeEach ->\n\t\t\t@token = \"some-opaque-token\"\n\t\t\t@req.params =\n\t\t\t\tProject_id: @project_id\n\t\t\t", "end": 12581, "score": 0.9886900186538696, "start": 12564, "tag": "KEY", "value": "some-opaque-token" }, { "context": "(),\n\t\t\t\tprojectId: @project_id,\n\t\t\t\ttargetEmail: 'user@example.com'\n\t\t\t\tcreatedAt: new Date(),\n\t\t\t}\n\t\t\t@fakeProject ", "end": 12960, "score": 0.9999250173568726, "start": 12944, "tag": "EMAIL", "value": "user@example.com" }, { "context": "\n\t\t\t\t_id: @fakeProject.owner_ref\n\t\t\t\tfirst_name: \"John\"\n\t\t\t\tlast_name: \"Doe\"\n\t\t\t\temail: \"john@example.co", "end": 13208, "score": 0.9998250603675842, "start": 13204, "tag": "NAME", "value": "John" }, { "context": ".owner_ref\n\t\t\t\tfirst_name: \"John\"\n\t\t\t\tlast_name: \"Doe\"\n\t\t\t\temail: \"john@example.com\"\n\n\t\t\t@Collaborators", "end": 13229, "score": 0.9996215105056763, "start": 13226, "tag": "NAME", "value": "Doe" }, { "context": "rst_name: \"John\"\n\t\t\t\tlast_name: \"Doe\"\n\t\t\t\temail: \"john@example.com\"\n\n\t\t\t@CollaboratorsHandler.isUserInvitedMemberOfP", "end": 13259, "score": 0.9999262690544128, "start": 13243, "tag": "EMAIL", "value": "john@example.com" }, { "context": "ject_id: @project_id\n\t\t\t\tinvite_id: @invite_id = \"thuseoautoh\"\n\t\t\t@req.session =\n\t\t\t\tuser: _id: @current_user_i", "end": 23460, "score": 0.9933404922485352, "start": 23449, "tag": "USERNAME", "value": "thuseoautoh" }, { "context": "ject_id: @project_id\n\t\t\t\tinvite_id: @invite_id = \"thuseoautoh\"\n\t\t\t@current_user =\n\t\t\t\t_id: @current_user_id = \"", "end": 25047, "score": 0.9399412870407104, "start": 25036, "tag": "USERNAME", "value": "thuseoautoh" }, { "context": "id = \"current-user-id\"\n\t\t\t@req.session =\n\t\t\t\tuser: @current_user\n\t\t\t@res.render = sinon.stub()\n\t\t\t@res.sendStatus ", "end": 25155, "score": 0.9909845590591431, "start": 25142, "tag": "USERNAME", "value": "@current_user" }, { "context": "\n\t\t\t\tProject_id: @project_id\n\t\t\t\ttoken: @token = \"mock-token\"\n\t\t\t@req.session =\n\t\t\t\tuser: _id: @current_u", "end": 26677, "score": 0.9128844738006592, "start": 26673, "tag": "PASSWORD", "value": "mock" }, { "context": "uldInviteEmail', ->\n\n\t\tbeforeEach ->\n\t\t\t@email = 'user@example.com'\n\n\t\tdescribe 'when we should be restricting to ex", "end": 28304, "score": 0.9999170303344727, "start": 28288, "tag": "EMAIL", "value": "user@example.com" }, { "context": "er account is absent', ->\n\n\t\t\t\tbeforeEach ->\n\t\t\t\t\t@user = null\n\t\t\t\t\t@UserGetter.getUserByAnyEmail = s", "end": 28977, "score": 0.7361276745796204, "start": 28977, "tag": "USERNAME", "value": "" } ]
test/unit/coffee/Collaborators/CollaboratorsInviteControllerTests.coffee
shyoshyo/web-sharelatex
1
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsInviteController.js" SandboxedModule = require('sandboxed-module') events = require "events" MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" ObjectId = require("mongojs").ObjectId describe "CollaboratorsInviteController", -> beforeEach -> @user = _id: 'id' @AnalyticsManger = recordEvent: sinon.stub() @sendingUser = null @AuthenticationController = getSessionUser: (req) => @sendingUser = req.session.user return @sendingUser @RateLimiter = addCount: sinon.stub @LimitationsManager = {} @UserGetter = getUserByAnyEmail: sinon.stub() getUser: sinon.stub() @CollaboratorsInviteController = SandboxedModule.require modulePath, requires: "../Project/ProjectGetter": @ProjectGetter = {} '../Subscription/LimitationsManager' : @LimitationsManager '../User/UserGetter': @UserGetter "./CollaboratorsHandler": @CollaboratorsHandler = {} "./CollaboratorsInviteHandler": @CollaboratorsInviteHandler = {} 'logger-sharelatex': @logger = {err: sinon.stub(), error: sinon.stub(), log: sinon.stub()} "../Editor/EditorRealTimeController": @EditorRealTimeController = {emitToRoom: sinon.stub()} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} "../Analytics/AnalyticsManager": @AnalyticsManger '../Authentication/AuthenticationController': @AuthenticationController 'settings-sharelatex': @settings = {} "../../infrastructure/RateLimiter":@RateLimiter @res = new MockResponse() @req = new MockRequest() @project_id = "project-id-123" @callback = sinon.stub() describe 'getAllInvites', -> beforeEach -> @fakeInvites = [ {_id: ObjectId(), one: 1}, {_id: ObjectId(), two: 2} ] @req.params = Project_id: @project_id @res.json = sinon.stub() @next = sinon.stub() describe 'when all goes well', -> beforeEach -> @CollaboratorsInviteHandler.getAllInvites = sinon.stub().callsArgWith(1, null, @fakeInvites) @CollaboratorsInviteController.getAllInvites @req, @res, @next it 'should not produce an error', -> @next.callCount.should.equal 0 it 'should produce a list of invite objects', -> @res.json.callCount.should.equal 1 @res.json.calledWith({invites: @fakeInvites}).should.equal true it 'should have called CollaboratorsInviteHandler.getAllInvites', -> @CollaboratorsInviteHandler.getAllInvites.callCount.should.equal 1 @CollaboratorsInviteHandler.getAllInvites.calledWith(@project_id).should.equal true describe 'when CollaboratorsInviteHandler.getAllInvites produces an error', -> beforeEach -> @CollaboratorsInviteHandler.getAllInvites = sinon.stub().callsArgWith(1, new Error('woops')) @CollaboratorsInviteController.getAllInvites @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe 'inviteToProject', -> beforeEach -> @targetEmail = "user@example.com" @req.params = Project_id: @project_id @current_user = _id: @current_user_id = "current-user-id" @req.session = user: @current_user @req.body = email: @targetEmail privileges: @privileges = "readAndWrite" @res.json = sinon.stub() @res.sendStatus = sinon.stub() @invite = { _id: ObjectId(), token: "htnseuthaouse", sendingUserId: @current_user_id, projectId: @targetEmail, targetEmail: 'user@example.com' createdAt: new Date(), } @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteHandler.inviteToProject = sinon.stub().callsArgWith(4, null, @invite) @err = new Error('woops') @callback = sinon.stub() @next = sinon.stub() describe 'when all goes well', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response', -> @res.json.callCount.should.equal 1 ({invite: @invite}).should.deep.equal(@res.json.firstCall.args[0]) it 'should have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 1 @LimitationsManager.canAddXCollaborators.calledWith(@project_id).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 1 @CollaboratorsInviteHandler.inviteToProject.calledWith(@project_id,@current_user,@targetEmail,@privileges).should.equal true it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when the user is not allowed to add more collaborators', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, false) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response without an invite', -> @res.json.callCount.should.equal 1 ({invite: null}).should.deep.equal(@res.json.firstCall.args[0]) it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when canAddXCollaborators produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, @err) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when inviteToProject produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @err = new Error('woops') @CollaboratorsInviteHandler.inviteToProject = sinon.stub().callsArgWith(4, @err) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 1 @LimitationsManager.canAddXCollaborators.calledWith(@project_id).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 1 @CollaboratorsInviteHandler.inviteToProject.calledWith(@project_id,@current_user,@targetEmail,@privileges).should.equal true describe 'when _checkShouldInviteEmail disallows the invite', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, false) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response with no invite, and an error property', -> @res.json.callCount.should.equal 1 ({invite: null, error: 'cannot_invite_non_user'}).should.deep.equal(@res.json.firstCall.args[0]) it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when _checkShouldInviteEmail produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, new Error('woops')) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when the user invites themselves to the project', -> beforeEach -> @req.session.user = {_id: 'abc', email: 'me@example.com'} @req.body.email = 'me@example.com' @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should reject action, return json response with error code', -> @res.json.callCount.should.equal 1 ({invite: null, error: 'cannot_invite_self'}).should.deep.equal(@res.json.firstCall.args[0]) it 'should not have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 0 it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 it 'should not have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 0 describe 'when _checkRateLimit returns false', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, false) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should send a 429 response', -> @res.sendStatus.calledWith(429).should.equal true it 'should not call inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.called.should.equal false it 'should not call emitToRoom', -> @EditorRealTimeController.emitToRoom.called.should.equal false describe "viewInvite", -> beforeEach -> @token = "some-opaque-token" @req.params = Project_id: @project_id token: @token @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.redirect = sinon.stub() @res.sendStatus = sinon.stub() @invite = { _id: ObjectId(), token: @token, sendingUserId: ObjectId(), projectId: @project_id, targetEmail: 'user@example.com' createdAt: new Date(), } @fakeProject = _id: @project_id name: "some project" owner_ref: @invite.sendingUserId collaberator_refs: [] readOnly_refs: [] @owner = _id: @fakeProject.owner_ref first_name: "John" last_name: "Doe" email: "john@example.com" @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, null, false, null) @CollaboratorsInviteHandler.getInviteByToken = sinon.stub().callsArgWith(2, null, @invite) @ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @fakeProject) @UserGetter.getUser.callsArgWith(2, null, @owner) @callback = sinon.stub() @next = sinon.stub() describe 'when the token is valid', -> beforeEach -> @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/show').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsInviteHandler.getInviteByToken.calledWith(@fakeProject._id, @invite.token).should.equal true it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 @ProjectGetter.getProject.calledWith(@project_id).should.equal true describe 'when user is already a member of the project', -> beforeEach -> @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, null, true, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should redirect to the project page', -> @res.redirect.callCount.should.equal 1 @res.redirect.calledWith("/project/#{@project_id}").should.equal true it 'should not call next with an error', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 0 it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when isUserInvitedMemberOfProject produces an error', -> beforeEach -> @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 0 it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when the getInviteByToken produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.getInviteByToken.callsArgWith(2, @err) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when the getInviteByToken does not produce an invite', -> beforeEach -> @CollaboratorsInviteHandler.getInviteByToken.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when User.getUser produces an error', -> beforeEach -> @UserGetter.getUser.callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when User.getUser does not find a user', -> beforeEach -> @UserGetter.getUser.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when getProject produces an error', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 describe 'when Project.getUser does not find a user', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 describe "resendInvite", -> beforeEach -> @req.params = Project_id: @project_id invite_id: @invite_id = "thuseoautoh" @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.sendStatus = sinon.stub() @CollaboratorsInviteHandler.resendInvite = sinon.stub().callsArgWith(3, null) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @callback = sinon.stub() @next = sinon.stub() describe 'when resendInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.resendInvite @req, @res, @next it 'should produce a 201 response', -> @res.sendStatus.callCount.should.equal 1 @res.sendStatus.calledWith(201).should.equal true it 'should have called resendInvite', -> @CollaboratorsInviteHandler.resendInvite.callCount.should.equal 1 it 'should check the rate limit', -> @CollaboratorsInviteController._checkRateLimit.callCount.should.equal 1 describe 'when resendInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.resendInvite = sinon.stub().callsArgWith(3, @err) @CollaboratorsInviteController.resendInvite @req, @res, @next it 'should not produce a 201 response', -> @res.sendStatus.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called resendInvite', -> @CollaboratorsInviteHandler.resendInvite.callCount.should.equal 1 describe "revokeInvite", -> beforeEach -> @req.params = Project_id: @project_id invite_id: @invite_id = "thuseoautoh" @current_user = _id: @current_user_id = "current-user-id" @req.session = user: @current_user @res.render = sinon.stub() @res.sendStatus = sinon.stub() @CollaboratorsInviteHandler.revokeInvite = sinon.stub().callsArgWith(2, null) @callback = sinon.stub() @next = sinon.stub() describe 'when revokeInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.revokeInvite @req, @res, @next it 'should produce a 201 response', -> @res.sendStatus.callCount.should.equal 1 @res.sendStatus.calledWith(201).should.equal true it 'should have called revokeInvite', -> @CollaboratorsInviteHandler.revokeInvite.callCount.should.equal 1 it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when revokeInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.revokeInvite = sinon.stub().callsArgWith(2, @err) @CollaboratorsInviteController.revokeInvite @req, @res, @next it 'should not produce a 201 response', -> @res.sendStatus.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called revokeInvite', -> @CollaboratorsInviteHandler.revokeInvite.callCount.should.equal 1 describe "acceptInvite", -> beforeEach -> @req.params = Project_id: @project_id token: @token = "mock-token" @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.redirect = sinon.stub() @CollaboratorsInviteHandler.acceptInvite = sinon.stub().callsArgWith(3, null) @callback = sinon.stub() @next = sinon.stub() describe 'when acceptInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.acceptInvite @req, @res, @next it 'should redirect to project page', () -> @res.redirect.callCount.should.equal 1 @res.redirect.calledWith("/project/#{@project_id}").should.equal true it 'should have called acceptInvite', -> @CollaboratorsInviteHandler.acceptInvite .calledWith(@project_id, @token) .should.equal true it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when revokeInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.acceptInvite = sinon.stub().callsArgWith(3, @err) @CollaboratorsInviteController.acceptInvite @req, @res, @next it 'should not redirect to project page', -> @res.redirect.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called acceptInvite', -> @CollaboratorsInviteHandler.acceptInvite.callCount.should.equal 1 describe '_checkShouldInviteEmail', -> beforeEach -> @email = 'user@example.com' describe 'when we should be restricting to existing accounts', -> beforeEach -> @settings.restrictInvitesToExistingAccounts = true @call = (callback) => @CollaboratorsInviteController._checkShouldInviteEmail @email, callback describe 'when user account is present', -> beforeEach -> @user = {_id: ObjectId().toString()} @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, null, @user) it 'should callback with `true`', (done) -> @call (err, shouldAllow) => expect(err).to.equal null expect(shouldAllow).to.equal true done() describe 'when user account is absent', -> beforeEach -> @user = null @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, null, @user) it 'should callback with `false`', (done) -> @call (err, shouldAllow) => expect(err).to.equal null expect(shouldAllow).to.equal false done() it 'should have called getUser', (done) -> @call (err, shouldAllow) => @UserGetter.getUserByAnyEmail.callCount.should.equal 1 @UserGetter.getUserByAnyEmail.calledWith(@email, {_id: 1}).should.equal true done() describe 'when getUser produces an error', -> beforeEach -> @user = null @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, new Error('woops')) it 'should callback with an error', (done) -> @call (err, shouldAllow) => expect(err).to.not.equal null expect(err).to.be.instanceof Error expect(shouldAllow).to.equal undefined done() describe '_checkRateLimit', -> beforeEach -> @settings.restrictInvitesToExistingAccounts = false @sendingUserId = "32312313" @LimitationsManager.allowedNumberOfCollaboratorsForUser = sinon.stub() @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null, 17) it 'should callback with `true` when rate limit under', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.called.should.equal true result.should.equal true done() it 'should callback with `false` when rate limit hit', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, false) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.called.should.equal true result.should.equal false done() it 'should call rate limiter with 10x the collaborators', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(170) done() it 'should call rate limiter with 200 when collaborators is -1', (done) -> @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null, -1) @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(200) done() it 'should call rate limiter with 10 when user has no collaborators set', (done) -> @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null) @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(10) done()
28867
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsInviteController.js" SandboxedModule = require('sandboxed-module') events = require "events" MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" ObjectId = require("mongojs").ObjectId describe "CollaboratorsInviteController", -> beforeEach -> @user = _id: 'id' @AnalyticsManger = recordEvent: sinon.stub() @sendingUser = null @AuthenticationController = getSessionUser: (req) => @sendingUser = req.session.user return @sendingUser @RateLimiter = addCount: sinon.stub @LimitationsManager = {} @UserGetter = getUserByAnyEmail: sinon.stub() getUser: sinon.stub() @CollaboratorsInviteController = SandboxedModule.require modulePath, requires: "../Project/ProjectGetter": @ProjectGetter = {} '../Subscription/LimitationsManager' : @LimitationsManager '../User/UserGetter': @UserGetter "./CollaboratorsHandler": @CollaboratorsHandler = {} "./CollaboratorsInviteHandler": @CollaboratorsInviteHandler = {} 'logger-sharelatex': @logger = {err: sinon.stub(), error: sinon.stub(), log: sinon.stub()} "../Editor/EditorRealTimeController": @EditorRealTimeController = {emitToRoom: sinon.stub()} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} "../Analytics/AnalyticsManager": @AnalyticsManger '../Authentication/AuthenticationController': @AuthenticationController 'settings-sharelatex': @settings = {} "../../infrastructure/RateLimiter":@RateLimiter @res = new MockResponse() @req = new MockRequest() @project_id = "project-id-123" @callback = sinon.stub() describe 'getAllInvites', -> beforeEach -> @fakeInvites = [ {_id: ObjectId(), one: 1}, {_id: ObjectId(), two: 2} ] @req.params = Project_id: @project_id @res.json = sinon.stub() @next = sinon.stub() describe 'when all goes well', -> beforeEach -> @CollaboratorsInviteHandler.getAllInvites = sinon.stub().callsArgWith(1, null, @fakeInvites) @CollaboratorsInviteController.getAllInvites @req, @res, @next it 'should not produce an error', -> @next.callCount.should.equal 0 it 'should produce a list of invite objects', -> @res.json.callCount.should.equal 1 @res.json.calledWith({invites: @fakeInvites}).should.equal true it 'should have called CollaboratorsInviteHandler.getAllInvites', -> @CollaboratorsInviteHandler.getAllInvites.callCount.should.equal 1 @CollaboratorsInviteHandler.getAllInvites.calledWith(@project_id).should.equal true describe 'when CollaboratorsInviteHandler.getAllInvites produces an error', -> beforeEach -> @CollaboratorsInviteHandler.getAllInvites = sinon.stub().callsArgWith(1, new Error('woops')) @CollaboratorsInviteController.getAllInvites @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe 'inviteToProject', -> beforeEach -> @targetEmail = "<EMAIL>" @req.params = Project_id: @project_id @current_user = _id: @current_user_id = "current-user-id" @req.session = user: @current_user @req.body = email: @targetEmail privileges: @privileges = "readAndWrite" @res.json = sinon.stub() @res.sendStatus = sinon.stub() @invite = { _id: ObjectId(), token: "<PASSWORD>", sendingUserId: @current_user_id, projectId: @targetEmail, targetEmail: '<EMAIL>' createdAt: new Date(), } @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteHandler.inviteToProject = sinon.stub().callsArgWith(4, null, @invite) @err = new Error('woops') @callback = sinon.stub() @next = sinon.stub() describe 'when all goes well', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response', -> @res.json.callCount.should.equal 1 ({invite: @invite}).should.deep.equal(@res.json.firstCall.args[0]) it 'should have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 1 @LimitationsManager.canAddXCollaborators.calledWith(@project_id).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 1 @CollaboratorsInviteHandler.inviteToProject.calledWith(@project_id,@current_user,@targetEmail,@privileges).should.equal true it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when the user is not allowed to add more collaborators', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, false) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response without an invite', -> @res.json.callCount.should.equal 1 ({invite: null}).should.deep.equal(@res.json.firstCall.args[0]) it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when canAddXCollaborators produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, @err) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when inviteToProject produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @err = new Error('woops') @CollaboratorsInviteHandler.inviteToProject = sinon.stub().callsArgWith(4, @err) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 1 @LimitationsManager.canAddXCollaborators.calledWith(@project_id).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 1 @CollaboratorsInviteHandler.inviteToProject.calledWith(@project_id,@current_user,@targetEmail,@privileges).should.equal true describe 'when _checkShouldInviteEmail disallows the invite', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, false) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response with no invite, and an error property', -> @res.json.callCount.should.equal 1 ({invite: null, error: 'cannot_invite_non_user'}).should.deep.equal(@res.json.firstCall.args[0]) it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when _checkShouldInviteEmail produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, new Error('woops')) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when the user invites themselves to the project', -> beforeEach -> @req.session.user = {_id: 'abc', email: '<EMAIL>'} @req.body.email = '<EMAIL>' @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should reject action, return json response with error code', -> @res.json.callCount.should.equal 1 ({invite: null, error: 'cannot_invite_self'}).should.deep.equal(@res.json.firstCall.args[0]) it 'should not have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 0 it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 it 'should not have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 0 describe 'when _checkRateLimit returns false', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, false) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should send a 429 response', -> @res.sendStatus.calledWith(429).should.equal true it 'should not call inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.called.should.equal false it 'should not call emitToRoom', -> @EditorRealTimeController.emitToRoom.called.should.equal false describe "viewInvite", -> beforeEach -> @token = "<KEY>" @req.params = Project_id: @project_id token: @token @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.redirect = sinon.stub() @res.sendStatus = sinon.stub() @invite = { _id: ObjectId(), token: @token, sendingUserId: ObjectId(), projectId: @project_id, targetEmail: '<EMAIL>' createdAt: new Date(), } @fakeProject = _id: @project_id name: "some project" owner_ref: @invite.sendingUserId collaberator_refs: [] readOnly_refs: [] @owner = _id: @fakeProject.owner_ref first_name: "<NAME>" last_name: "<NAME>" email: "<EMAIL>" @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, null, false, null) @CollaboratorsInviteHandler.getInviteByToken = sinon.stub().callsArgWith(2, null, @invite) @ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @fakeProject) @UserGetter.getUser.callsArgWith(2, null, @owner) @callback = sinon.stub() @next = sinon.stub() describe 'when the token is valid', -> beforeEach -> @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/show').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsInviteHandler.getInviteByToken.calledWith(@fakeProject._id, @invite.token).should.equal true it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 @ProjectGetter.getProject.calledWith(@project_id).should.equal true describe 'when user is already a member of the project', -> beforeEach -> @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, null, true, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should redirect to the project page', -> @res.redirect.callCount.should.equal 1 @res.redirect.calledWith("/project/#{@project_id}").should.equal true it 'should not call next with an error', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 0 it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when isUserInvitedMemberOfProject produces an error', -> beforeEach -> @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 0 it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when the getInviteByToken produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.getInviteByToken.callsArgWith(2, @err) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when the getInviteByToken does not produce an invite', -> beforeEach -> @CollaboratorsInviteHandler.getInviteByToken.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when User.getUser produces an error', -> beforeEach -> @UserGetter.getUser.callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when User.getUser does not find a user', -> beforeEach -> @UserGetter.getUser.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when getProject produces an error', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 describe 'when Project.getUser does not find a user', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 describe "resendInvite", -> beforeEach -> @req.params = Project_id: @project_id invite_id: @invite_id = "thuseoautoh" @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.sendStatus = sinon.stub() @CollaboratorsInviteHandler.resendInvite = sinon.stub().callsArgWith(3, null) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @callback = sinon.stub() @next = sinon.stub() describe 'when resendInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.resendInvite @req, @res, @next it 'should produce a 201 response', -> @res.sendStatus.callCount.should.equal 1 @res.sendStatus.calledWith(201).should.equal true it 'should have called resendInvite', -> @CollaboratorsInviteHandler.resendInvite.callCount.should.equal 1 it 'should check the rate limit', -> @CollaboratorsInviteController._checkRateLimit.callCount.should.equal 1 describe 'when resendInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.resendInvite = sinon.stub().callsArgWith(3, @err) @CollaboratorsInviteController.resendInvite @req, @res, @next it 'should not produce a 201 response', -> @res.sendStatus.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called resendInvite', -> @CollaboratorsInviteHandler.resendInvite.callCount.should.equal 1 describe "revokeInvite", -> beforeEach -> @req.params = Project_id: @project_id invite_id: @invite_id = "thuseoautoh" @current_user = _id: @current_user_id = "current-user-id" @req.session = user: @current_user @res.render = sinon.stub() @res.sendStatus = sinon.stub() @CollaboratorsInviteHandler.revokeInvite = sinon.stub().callsArgWith(2, null) @callback = sinon.stub() @next = sinon.stub() describe 'when revokeInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.revokeInvite @req, @res, @next it 'should produce a 201 response', -> @res.sendStatus.callCount.should.equal 1 @res.sendStatus.calledWith(201).should.equal true it 'should have called revokeInvite', -> @CollaboratorsInviteHandler.revokeInvite.callCount.should.equal 1 it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when revokeInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.revokeInvite = sinon.stub().callsArgWith(2, @err) @CollaboratorsInviteController.revokeInvite @req, @res, @next it 'should not produce a 201 response', -> @res.sendStatus.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called revokeInvite', -> @CollaboratorsInviteHandler.revokeInvite.callCount.should.equal 1 describe "acceptInvite", -> beforeEach -> @req.params = Project_id: @project_id token: @token = "<PASSWORD>-token" @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.redirect = sinon.stub() @CollaboratorsInviteHandler.acceptInvite = sinon.stub().callsArgWith(3, null) @callback = sinon.stub() @next = sinon.stub() describe 'when acceptInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.acceptInvite @req, @res, @next it 'should redirect to project page', () -> @res.redirect.callCount.should.equal 1 @res.redirect.calledWith("/project/#{@project_id}").should.equal true it 'should have called acceptInvite', -> @CollaboratorsInviteHandler.acceptInvite .calledWith(@project_id, @token) .should.equal true it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when revokeInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.acceptInvite = sinon.stub().callsArgWith(3, @err) @CollaboratorsInviteController.acceptInvite @req, @res, @next it 'should not redirect to project page', -> @res.redirect.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called acceptInvite', -> @CollaboratorsInviteHandler.acceptInvite.callCount.should.equal 1 describe '_checkShouldInviteEmail', -> beforeEach -> @email = '<EMAIL>' describe 'when we should be restricting to existing accounts', -> beforeEach -> @settings.restrictInvitesToExistingAccounts = true @call = (callback) => @CollaboratorsInviteController._checkShouldInviteEmail @email, callback describe 'when user account is present', -> beforeEach -> @user = {_id: ObjectId().toString()} @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, null, @user) it 'should callback with `true`', (done) -> @call (err, shouldAllow) => expect(err).to.equal null expect(shouldAllow).to.equal true done() describe 'when user account is absent', -> beforeEach -> @user = null @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, null, @user) it 'should callback with `false`', (done) -> @call (err, shouldAllow) => expect(err).to.equal null expect(shouldAllow).to.equal false done() it 'should have called getUser', (done) -> @call (err, shouldAllow) => @UserGetter.getUserByAnyEmail.callCount.should.equal 1 @UserGetter.getUserByAnyEmail.calledWith(@email, {_id: 1}).should.equal true done() describe 'when getUser produces an error', -> beforeEach -> @user = null @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, new Error('woops')) it 'should callback with an error', (done) -> @call (err, shouldAllow) => expect(err).to.not.equal null expect(err).to.be.instanceof Error expect(shouldAllow).to.equal undefined done() describe '_checkRateLimit', -> beforeEach -> @settings.restrictInvitesToExistingAccounts = false @sendingUserId = "32312313" @LimitationsManager.allowedNumberOfCollaboratorsForUser = sinon.stub() @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null, 17) it 'should callback with `true` when rate limit under', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.called.should.equal true result.should.equal true done() it 'should callback with `false` when rate limit hit', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, false) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.called.should.equal true result.should.equal false done() it 'should call rate limiter with 10x the collaborators', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(170) done() it 'should call rate limiter with 200 when collaborators is -1', (done) -> @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null, -1) @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(200) done() it 'should call rate limiter with 10 when user has no collaborators set', (done) -> @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null) @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(10) done()
true
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsInviteController.js" SandboxedModule = require('sandboxed-module') events = require "events" MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" ObjectId = require("mongojs").ObjectId describe "CollaboratorsInviteController", -> beforeEach -> @user = _id: 'id' @AnalyticsManger = recordEvent: sinon.stub() @sendingUser = null @AuthenticationController = getSessionUser: (req) => @sendingUser = req.session.user return @sendingUser @RateLimiter = addCount: sinon.stub @LimitationsManager = {} @UserGetter = getUserByAnyEmail: sinon.stub() getUser: sinon.stub() @CollaboratorsInviteController = SandboxedModule.require modulePath, requires: "../Project/ProjectGetter": @ProjectGetter = {} '../Subscription/LimitationsManager' : @LimitationsManager '../User/UserGetter': @UserGetter "./CollaboratorsHandler": @CollaboratorsHandler = {} "./CollaboratorsInviteHandler": @CollaboratorsInviteHandler = {} 'logger-sharelatex': @logger = {err: sinon.stub(), error: sinon.stub(), log: sinon.stub()} "../Editor/EditorRealTimeController": @EditorRealTimeController = {emitToRoom: sinon.stub()} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} "../Analytics/AnalyticsManager": @AnalyticsManger '../Authentication/AuthenticationController': @AuthenticationController 'settings-sharelatex': @settings = {} "../../infrastructure/RateLimiter":@RateLimiter @res = new MockResponse() @req = new MockRequest() @project_id = "project-id-123" @callback = sinon.stub() describe 'getAllInvites', -> beforeEach -> @fakeInvites = [ {_id: ObjectId(), one: 1}, {_id: ObjectId(), two: 2} ] @req.params = Project_id: @project_id @res.json = sinon.stub() @next = sinon.stub() describe 'when all goes well', -> beforeEach -> @CollaboratorsInviteHandler.getAllInvites = sinon.stub().callsArgWith(1, null, @fakeInvites) @CollaboratorsInviteController.getAllInvites @req, @res, @next it 'should not produce an error', -> @next.callCount.should.equal 0 it 'should produce a list of invite objects', -> @res.json.callCount.should.equal 1 @res.json.calledWith({invites: @fakeInvites}).should.equal true it 'should have called CollaboratorsInviteHandler.getAllInvites', -> @CollaboratorsInviteHandler.getAllInvites.callCount.should.equal 1 @CollaboratorsInviteHandler.getAllInvites.calledWith(@project_id).should.equal true describe 'when CollaboratorsInviteHandler.getAllInvites produces an error', -> beforeEach -> @CollaboratorsInviteHandler.getAllInvites = sinon.stub().callsArgWith(1, new Error('woops')) @CollaboratorsInviteController.getAllInvites @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe 'inviteToProject', -> beforeEach -> @targetEmail = "PI:EMAIL:<EMAIL>END_PI" @req.params = Project_id: @project_id @current_user = _id: @current_user_id = "current-user-id" @req.session = user: @current_user @req.body = email: @targetEmail privileges: @privileges = "readAndWrite" @res.json = sinon.stub() @res.sendStatus = sinon.stub() @invite = { _id: ObjectId(), token: "PI:PASSWORD:<PASSWORD>END_PI", sendingUserId: @current_user_id, projectId: @targetEmail, targetEmail: 'PI:EMAIL:<EMAIL>END_PI' createdAt: new Date(), } @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteHandler.inviteToProject = sinon.stub().callsArgWith(4, null, @invite) @err = new Error('woops') @callback = sinon.stub() @next = sinon.stub() describe 'when all goes well', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response', -> @res.json.callCount.should.equal 1 ({invite: @invite}).should.deep.equal(@res.json.firstCall.args[0]) it 'should have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 1 @LimitationsManager.canAddXCollaborators.calledWith(@project_id).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 1 @CollaboratorsInviteHandler.inviteToProject.calledWith(@project_id,@current_user,@targetEmail,@privileges).should.equal true it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when the user is not allowed to add more collaborators', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, false) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response without an invite', -> @res.json.callCount.should.equal 1 ({invite: null}).should.deep.equal(@res.json.firstCall.args[0]) it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when canAddXCollaborators produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, @err) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@sendingUser, @targetEmail).should.equal false it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when inviteToProject produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @err = new Error('woops') @CollaboratorsInviteHandler.inviteToProject = sinon.stub().callsArgWith(4, @err) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 1 @LimitationsManager.canAddXCollaborators.calledWith(@project_id).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 1 @CollaboratorsInviteHandler.inviteToProject.calledWith(@project_id,@current_user,@targetEmail,@privileges).should.equal true describe 'when _checkShouldInviteEmail disallows the invite', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, false) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should produce json response with no invite, and an error property', -> @res.json.callCount.should.equal 1 ({invite: null, error: 'cannot_invite_non_user'}).should.deep.equal(@res.json.firstCall.args[0]) it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when _checkShouldInviteEmail produces an error', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, new Error('woops')) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 1 @CollaboratorsInviteController._checkShouldInviteEmail.calledWith(@targetEmail).should.equal true it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 describe 'when the user invites themselves to the project', -> beforeEach -> @req.session.user = {_id: 'abc', email: 'PI:EMAIL:<EMAIL>END_PI'} @req.body.email = 'PI:EMAIL:<EMAIL>END_PI' @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should reject action, return json response with error code', -> @res.json.callCount.should.equal 1 ({invite: null, error: 'cannot_invite_self'}).should.deep.equal(@res.json.firstCall.args[0]) it 'should not have called canAddXCollaborators', -> @LimitationsManager.canAddXCollaborators.callCount.should.equal 0 it 'should not have called _checkShouldInviteEmail', -> @CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal 0 it 'should not have called inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.callCount.should.equal 0 it 'should not have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 0 describe 'when _checkRateLimit returns false', -> beforeEach -> @CollaboratorsInviteController._checkShouldInviteEmail = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, false) @LimitationsManager.canAddXCollaborators = sinon.stub().callsArgWith(2, null, true) @CollaboratorsInviteController.inviteToProject @req, @res, @next it 'should send a 429 response', -> @res.sendStatus.calledWith(429).should.equal true it 'should not call inviteToProject', -> @CollaboratorsInviteHandler.inviteToProject.called.should.equal false it 'should not call emitToRoom', -> @EditorRealTimeController.emitToRoom.called.should.equal false describe "viewInvite", -> beforeEach -> @token = "PI:KEY:<KEY>END_PI" @req.params = Project_id: @project_id token: @token @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.redirect = sinon.stub() @res.sendStatus = sinon.stub() @invite = { _id: ObjectId(), token: @token, sendingUserId: ObjectId(), projectId: @project_id, targetEmail: 'PI:EMAIL:<EMAIL>END_PI' createdAt: new Date(), } @fakeProject = _id: @project_id name: "some project" owner_ref: @invite.sendingUserId collaberator_refs: [] readOnly_refs: [] @owner = _id: @fakeProject.owner_ref first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" email: "PI:EMAIL:<EMAIL>END_PI" @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, null, false, null) @CollaboratorsInviteHandler.getInviteByToken = sinon.stub().callsArgWith(2, null, @invite) @ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @fakeProject) @UserGetter.getUser.callsArgWith(2, null, @owner) @callback = sinon.stub() @next = sinon.stub() describe 'when the token is valid', -> beforeEach -> @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/show').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsInviteHandler.getInviteByToken.calledWith(@fakeProject._id, @invite.token).should.equal true it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 @ProjectGetter.getProject.calledWith(@project_id).should.equal true describe 'when user is already a member of the project', -> beforeEach -> @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, null, true, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should redirect to the project page', -> @res.redirect.callCount.should.equal 1 @res.redirect.calledWith("/project/#{@project_id}").should.equal true it 'should not call next with an error', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 0 it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when isUserInvitedMemberOfProject produces an error', -> beforeEach -> @CollaboratorsHandler.isUserInvitedMemberOfProject = sinon.stub().callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should call next with an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 0 it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when the getInviteByToken produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.getInviteByToken.callsArgWith(2, @err) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when the getInviteByToken does not produce an invite', -> beforeEach -> @CollaboratorsInviteHandler.getInviteByToken.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should not call User.getUser', -> @UserGetter.getUser.callCount.should.equal 0 it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when User.getUser produces an error', -> beforeEach -> @UserGetter.getUser.callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when User.getUser does not find a user', -> beforeEach -> @UserGetter.getUser.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should not call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 0 describe 'when getProject produces an error', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, new Error('woops')) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should produce an error', -> @next.callCount.should.equal 1 expect(@next.firstCall.args[0]).to.be.instanceof Error it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call User.getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 describe 'when Project.getUser does not find a user', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, null, null) @CollaboratorsInviteController.viewInvite @req, @res, @next it 'should render the not-valid view template', -> @res.render.callCount.should.equal 1 @res.render.calledWith('project/invite/not-valid').should.equal true it 'should not call next', -> @next.callCount.should.equal 0 it 'should call CollaboratorsHandler.isUserInvitedMemberOfProject', -> @CollaboratorsHandler.isUserInvitedMemberOfProject.callCount.should.equal 1 @CollaboratorsHandler.isUserInvitedMemberOfProject.calledWith(@current_user_id, @project_id).should.equal true it 'should call getInviteByToken', -> @CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal 1 it 'should call getUser', -> @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({_id: @fakeProject.owner_ref}).should.equal true it 'should call ProjectGetter.getProject', -> @ProjectGetter.getProject.callCount.should.equal 1 describe "resendInvite", -> beforeEach -> @req.params = Project_id: @project_id invite_id: @invite_id = "thuseoautoh" @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.sendStatus = sinon.stub() @CollaboratorsInviteHandler.resendInvite = sinon.stub().callsArgWith(3, null) @CollaboratorsInviteController._checkRateLimit = sinon.stub().yields(null, true) @callback = sinon.stub() @next = sinon.stub() describe 'when resendInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.resendInvite @req, @res, @next it 'should produce a 201 response', -> @res.sendStatus.callCount.should.equal 1 @res.sendStatus.calledWith(201).should.equal true it 'should have called resendInvite', -> @CollaboratorsInviteHandler.resendInvite.callCount.should.equal 1 it 'should check the rate limit', -> @CollaboratorsInviteController._checkRateLimit.callCount.should.equal 1 describe 'when resendInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.resendInvite = sinon.stub().callsArgWith(3, @err) @CollaboratorsInviteController.resendInvite @req, @res, @next it 'should not produce a 201 response', -> @res.sendStatus.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called resendInvite', -> @CollaboratorsInviteHandler.resendInvite.callCount.should.equal 1 describe "revokeInvite", -> beforeEach -> @req.params = Project_id: @project_id invite_id: @invite_id = "thuseoautoh" @current_user = _id: @current_user_id = "current-user-id" @req.session = user: @current_user @res.render = sinon.stub() @res.sendStatus = sinon.stub() @CollaboratorsInviteHandler.revokeInvite = sinon.stub().callsArgWith(2, null) @callback = sinon.stub() @next = sinon.stub() describe 'when revokeInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.revokeInvite @req, @res, @next it 'should produce a 201 response', -> @res.sendStatus.callCount.should.equal 1 @res.sendStatus.calledWith(201).should.equal true it 'should have called revokeInvite', -> @CollaboratorsInviteHandler.revokeInvite.callCount.should.equal 1 it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when revokeInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.revokeInvite = sinon.stub().callsArgWith(2, @err) @CollaboratorsInviteController.revokeInvite @req, @res, @next it 'should not produce a 201 response', -> @res.sendStatus.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called revokeInvite', -> @CollaboratorsInviteHandler.revokeInvite.callCount.should.equal 1 describe "acceptInvite", -> beforeEach -> @req.params = Project_id: @project_id token: @token = "PI:PASSWORD:<PASSWORD>END_PI-token" @req.session = user: _id: @current_user_id = "current-user-id" @res.render = sinon.stub() @res.redirect = sinon.stub() @CollaboratorsInviteHandler.acceptInvite = sinon.stub().callsArgWith(3, null) @callback = sinon.stub() @next = sinon.stub() describe 'when acceptInvite does not produce an error', -> beforeEach -> @CollaboratorsInviteController.acceptInvite @req, @res, @next it 'should redirect to project page', () -> @res.redirect.callCount.should.equal 1 @res.redirect.calledWith("/project/#{@project_id}").should.equal true it 'should have called acceptInvite', -> @CollaboratorsInviteHandler.acceptInvite .calledWith(@project_id, @token) .should.equal true it 'should have called emitToRoom', -> @EditorRealTimeController.emitToRoom.callCount.should.equal 1 @EditorRealTimeController.emitToRoom.calledWith(@project_id, 'project:membership:changed').should.equal true describe 'when revokeInvite produces an error', -> beforeEach -> @err = new Error('woops') @CollaboratorsInviteHandler.acceptInvite = sinon.stub().callsArgWith(3, @err) @CollaboratorsInviteController.acceptInvite @req, @res, @next it 'should not redirect to project page', -> @res.redirect.callCount.should.equal 0 it 'should call next with the error', -> @next.callCount.should.equal 1 @next.calledWith(@err).should.equal true it 'should have called acceptInvite', -> @CollaboratorsInviteHandler.acceptInvite.callCount.should.equal 1 describe '_checkShouldInviteEmail', -> beforeEach -> @email = 'PI:EMAIL:<EMAIL>END_PI' describe 'when we should be restricting to existing accounts', -> beforeEach -> @settings.restrictInvitesToExistingAccounts = true @call = (callback) => @CollaboratorsInviteController._checkShouldInviteEmail @email, callback describe 'when user account is present', -> beforeEach -> @user = {_id: ObjectId().toString()} @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, null, @user) it 'should callback with `true`', (done) -> @call (err, shouldAllow) => expect(err).to.equal null expect(shouldAllow).to.equal true done() describe 'when user account is absent', -> beforeEach -> @user = null @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, null, @user) it 'should callback with `false`', (done) -> @call (err, shouldAllow) => expect(err).to.equal null expect(shouldAllow).to.equal false done() it 'should have called getUser', (done) -> @call (err, shouldAllow) => @UserGetter.getUserByAnyEmail.callCount.should.equal 1 @UserGetter.getUserByAnyEmail.calledWith(@email, {_id: 1}).should.equal true done() describe 'when getUser produces an error', -> beforeEach -> @user = null @UserGetter.getUserByAnyEmail = sinon.stub().callsArgWith(2, new Error('woops')) it 'should callback with an error', (done) -> @call (err, shouldAllow) => expect(err).to.not.equal null expect(err).to.be.instanceof Error expect(shouldAllow).to.equal undefined done() describe '_checkRateLimit', -> beforeEach -> @settings.restrictInvitesToExistingAccounts = false @sendingUserId = "32312313" @LimitationsManager.allowedNumberOfCollaboratorsForUser = sinon.stub() @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null, 17) it 'should callback with `true` when rate limit under', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.called.should.equal true result.should.equal true done() it 'should callback with `false` when rate limit hit', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, false) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.called.should.equal true result.should.equal false done() it 'should call rate limiter with 10x the collaborators', (done) -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(170) done() it 'should call rate limiter with 200 when collaborators is -1', (done) -> @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null, -1) @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(200) done() it 'should call rate limiter with 10 when user has no collaborators set', (done) -> @LimitationsManager.allowedNumberOfCollaboratorsForUser.withArgs(@sendingUserId).yields(null) @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @CollaboratorsInviteController._checkRateLimit @sendingUserId, (err, result)=> @RateLimiter.addCount.args[0][0].throttle.should.equal(10) done()
[ { "context": " else \"unknown\"\n\n clientData =\n name: info.name\n project: projectId\n session_id: sessio", "end": 2862, "score": 0.7214862704277039, "start": 2853, "tag": "NAME", "value": "info.name" } ]
src/backend/clients.coffee
tonistiigi/styler
18
fs = require "fs" {_} = require "underscore" useragent = require 'useragent' {Projects, Clients, Settings} = require "./data" {isAllowedIP} = require './utils' log = require './log' io = global.io # Call an async method in client's side. exports.callClient = (clientId, method, params={}, cb=->) -> client = Clients.get clientId if method == 'focus' id = (params.title || clientId) io.of('/info').emit 'focus', id else client?.socket?.emit "callclient", method, params, (response) -> cb response # Returns keyboard shortcuts that are also sent to client side. getKeyCommands = -> keyboard_shortcuts = Settings.at(0).get "keyboard_shortcuts" keys = {} for key in ["toggle-window-mode", "start-inspector-mode", "toggle-iframe-container"] keys[key] = keyboard_shortcuts[key].export keys # Info namespace is used in extensions to detect if daemon is running. io.of("/info").on 'connection', (socket) -> return socket.disconnect() unless isAllowedIP global.allowed, socket.handshake.address.address # Check if url is part of some project. socket.on 'checkproject', (url, cb) -> cb !!Projects.find (p) -> 0 == url.indexOf p.get("baseurl") # Client connection handler. io.of("/clients").on 'connection', (socket) -> return socket.disconnect() unless isAllowedIP global.allowed, socket.handshake.address.address client = null onClientRegistred = (_client) -> client = _client client.socket = socket socket.emit 'registered', client.id, client.get('session_id'), getKeyCommands() projectId = client.get "project" if projectId sendBaseURL = -> socket.emit 'baseurl', Projects.get(projectId).get 'baseurl' Projects.get(projectId).bind 'change:baseurl', sendBaseURL sendBaseURL() log.info id: client.id, project: projectId, url: client.get 'url', 'Client connected' socket.on "register", (info) -> projectId = 0 if info.url? project = Projects.find (project) -> (info.url.indexOf project.get 'baseurl') == 0 projectId = project.id if project (require "./console").getConsole projectId if projectId sessionId = parseInt info.sessionId, 10 client = Clients.find (o) -> o.get('session_id') == sessionId if client if client.get("project") != projectId || client.get("connected") client = null sessionId = ~~ (Math.random() * 1e8) agent = useragent.parse info.useragent agenttype = switch (agent.family.split " ")[0].toLowerCase() when "chrome" then "chrome" when "firefox" then "firefox" when "safari" then "safari" when "opera" then "opera" when "ie" then "ie" when "ipad" then "ipad" when "iphone", "ipod" then "iphone" when "android" then "android" when "blackberry" then "blackberry" else "unknown" clientData = name: info.name project: projectId session_id: sessionId url: info.url useragent: agent.toString() css: info.css embed: info.embed connected: true agenttype: agenttype lastTime: (new Date()).getTime() if client clearTimeout client._clientRemoveTimeout client.save clientData, success: onClientRegistred, wait: true else Clients.create clientData, success: onClientRegistred, wait: true socket.on "change:stylesheets", (stylesheets) -> return unless client current = client.get "css" client.save css: current.concat (sheet for sheet in stylesheets) #direct messages from the page. like inspect started with keyboard shortcut socket.on "clientmessage", (name, params) -> return unless client projectId = client.get('project') (require "./console").getConsole(projectId)?.onClientMessage name, params socket.on "disconnect", -> return unless client client.save connected: false client._clientRemoveTimeout = setTimeout (-> client.destroy()), 4e3 log.debug id: client.id, 'Client disconnected'
44539
fs = require "fs" {_} = require "underscore" useragent = require 'useragent' {Projects, Clients, Settings} = require "./data" {isAllowedIP} = require './utils' log = require './log' io = global.io # Call an async method in client's side. exports.callClient = (clientId, method, params={}, cb=->) -> client = Clients.get clientId if method == 'focus' id = (params.title || clientId) io.of('/info').emit 'focus', id else client?.socket?.emit "callclient", method, params, (response) -> cb response # Returns keyboard shortcuts that are also sent to client side. getKeyCommands = -> keyboard_shortcuts = Settings.at(0).get "keyboard_shortcuts" keys = {} for key in ["toggle-window-mode", "start-inspector-mode", "toggle-iframe-container"] keys[key] = keyboard_shortcuts[key].export keys # Info namespace is used in extensions to detect if daemon is running. io.of("/info").on 'connection', (socket) -> return socket.disconnect() unless isAllowedIP global.allowed, socket.handshake.address.address # Check if url is part of some project. socket.on 'checkproject', (url, cb) -> cb !!Projects.find (p) -> 0 == url.indexOf p.get("baseurl") # Client connection handler. io.of("/clients").on 'connection', (socket) -> return socket.disconnect() unless isAllowedIP global.allowed, socket.handshake.address.address client = null onClientRegistred = (_client) -> client = _client client.socket = socket socket.emit 'registered', client.id, client.get('session_id'), getKeyCommands() projectId = client.get "project" if projectId sendBaseURL = -> socket.emit 'baseurl', Projects.get(projectId).get 'baseurl' Projects.get(projectId).bind 'change:baseurl', sendBaseURL sendBaseURL() log.info id: client.id, project: projectId, url: client.get 'url', 'Client connected' socket.on "register", (info) -> projectId = 0 if info.url? project = Projects.find (project) -> (info.url.indexOf project.get 'baseurl') == 0 projectId = project.id if project (require "./console").getConsole projectId if projectId sessionId = parseInt info.sessionId, 10 client = Clients.find (o) -> o.get('session_id') == sessionId if client if client.get("project") != projectId || client.get("connected") client = null sessionId = ~~ (Math.random() * 1e8) agent = useragent.parse info.useragent agenttype = switch (agent.family.split " ")[0].toLowerCase() when "chrome" then "chrome" when "firefox" then "firefox" when "safari" then "safari" when "opera" then "opera" when "ie" then "ie" when "ipad" then "ipad" when "iphone", "ipod" then "iphone" when "android" then "android" when "blackberry" then "blackberry" else "unknown" clientData = name: <NAME> project: projectId session_id: sessionId url: info.url useragent: agent.toString() css: info.css embed: info.embed connected: true agenttype: agenttype lastTime: (new Date()).getTime() if client clearTimeout client._clientRemoveTimeout client.save clientData, success: onClientRegistred, wait: true else Clients.create clientData, success: onClientRegistred, wait: true socket.on "change:stylesheets", (stylesheets) -> return unless client current = client.get "css" client.save css: current.concat (sheet for sheet in stylesheets) #direct messages from the page. like inspect started with keyboard shortcut socket.on "clientmessage", (name, params) -> return unless client projectId = client.get('project') (require "./console").getConsole(projectId)?.onClientMessage name, params socket.on "disconnect", -> return unless client client.save connected: false client._clientRemoveTimeout = setTimeout (-> client.destroy()), 4e3 log.debug id: client.id, 'Client disconnected'
true
fs = require "fs" {_} = require "underscore" useragent = require 'useragent' {Projects, Clients, Settings} = require "./data" {isAllowedIP} = require './utils' log = require './log' io = global.io # Call an async method in client's side. exports.callClient = (clientId, method, params={}, cb=->) -> client = Clients.get clientId if method == 'focus' id = (params.title || clientId) io.of('/info').emit 'focus', id else client?.socket?.emit "callclient", method, params, (response) -> cb response # Returns keyboard shortcuts that are also sent to client side. getKeyCommands = -> keyboard_shortcuts = Settings.at(0).get "keyboard_shortcuts" keys = {} for key in ["toggle-window-mode", "start-inspector-mode", "toggle-iframe-container"] keys[key] = keyboard_shortcuts[key].export keys # Info namespace is used in extensions to detect if daemon is running. io.of("/info").on 'connection', (socket) -> return socket.disconnect() unless isAllowedIP global.allowed, socket.handshake.address.address # Check if url is part of some project. socket.on 'checkproject', (url, cb) -> cb !!Projects.find (p) -> 0 == url.indexOf p.get("baseurl") # Client connection handler. io.of("/clients").on 'connection', (socket) -> return socket.disconnect() unless isAllowedIP global.allowed, socket.handshake.address.address client = null onClientRegistred = (_client) -> client = _client client.socket = socket socket.emit 'registered', client.id, client.get('session_id'), getKeyCommands() projectId = client.get "project" if projectId sendBaseURL = -> socket.emit 'baseurl', Projects.get(projectId).get 'baseurl' Projects.get(projectId).bind 'change:baseurl', sendBaseURL sendBaseURL() log.info id: client.id, project: projectId, url: client.get 'url', 'Client connected' socket.on "register", (info) -> projectId = 0 if info.url? project = Projects.find (project) -> (info.url.indexOf project.get 'baseurl') == 0 projectId = project.id if project (require "./console").getConsole projectId if projectId sessionId = parseInt info.sessionId, 10 client = Clients.find (o) -> o.get('session_id') == sessionId if client if client.get("project") != projectId || client.get("connected") client = null sessionId = ~~ (Math.random() * 1e8) agent = useragent.parse info.useragent agenttype = switch (agent.family.split " ")[0].toLowerCase() when "chrome" then "chrome" when "firefox" then "firefox" when "safari" then "safari" when "opera" then "opera" when "ie" then "ie" when "ipad" then "ipad" when "iphone", "ipod" then "iphone" when "android" then "android" when "blackberry" then "blackberry" else "unknown" clientData = name: PI:NAME:<NAME>END_PI project: projectId session_id: sessionId url: info.url useragent: agent.toString() css: info.css embed: info.embed connected: true agenttype: agenttype lastTime: (new Date()).getTime() if client clearTimeout client._clientRemoveTimeout client.save clientData, success: onClientRegistred, wait: true else Clients.create clientData, success: onClientRegistred, wait: true socket.on "change:stylesheets", (stylesheets) -> return unless client current = client.get "css" client.save css: current.concat (sheet for sheet in stylesheets) #direct messages from the page. like inspect started with keyboard shortcut socket.on "clientmessage", (name, params) -> return unless client projectId = client.get('project') (require "./console").getConsole(projectId)?.onClientMessage name, params socket.on "disconnect", -> return unless client client.save connected: false client._clientRemoveTimeout = setTimeout (-> client.destroy()), 4e3 log.debug id: client.id, 'Client disconnected'
[ { "context": "uest = \n\t\t\theaders:\n\t\t\t\t'sec-websocket-key1': \", 3524 2h 70M U|580 . t?[T\"\n\t\t\t\t'sec-websocket-key2': \"g", "end": 445, "score": 0.9317595362663269, "start": 438, "tag": "KEY", "value": "3524 2h" }, { "context": "\t\theaders:\n\t\t\t\t'sec-websocket-key1': \", 3524 2h 70M U|580 . t?[T\"\n\t\t\t\t'sec-websocket-key2': \"g29968", "end": 450, "score": 0.9319204688072205, "start": 447, "tag": "KEY", "value": "70M" }, { "context": "rs:\n\t\t\t\t'sec-websocket-key1': \", 3524 2h 70M U|580 . t?[T\"\n\t\t\t\t'sec-websocket-key2': \"g299681m859\\", "end": 456, "score": 0.8564989566802979, "start": 454, "tag": "KEY", "value": "80" }, { "context": "h 70M U|580 . t?[T\"\n\t\t\t\t'sec-websocket-key2': \"g299681m859\\\\ 8\"\n\t\t\t\torigin: \"localhost\"\n\t\t\t\thost: \"localhost\"\n\t\t", "end": 510, "score": 0.999582827091217, "start": 494, "tag": "KEY", "value": "g299681m859\\\\ 8" } ]
spec/client_spec.coffee
petrjanda/platformjs
1
require './spec_helper' Client = require 'client' sys = require 'sys' net = require 'net' buffer = require 'buffer' http = require 'http' Server = require 'server' WebSocket = require('websocket-client').WebSocket describe "Client", -> beforeEach -> @socket = setTimeout: () -> setEncoding: () -> setKeepAlive: () -> on: () -> write: () -> writable: true @request = headers: 'sec-websocket-key1': ", 3524 2h 70M U|580 . t?[T" 'sec-websocket-key2': "g299681m859\\ 8" origin: "localhost" host: "localhost" socket: @socket @head = new buffer.Buffer(['\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00']) @client = new Client("", @request, @socket, @head) @client.head = @head it "should be valid", -> expect(@client).toBeDefined() describe "dataHandler", -> xit "should set status to CLOSING if data is empty", -> describe "send", -> it "should not write to socket if client is not in READY state", -> @client.state = Client.STATUS_HANDSHAKING spyOn @client, 'write' @client.send("data") expect(@client.write).not.toHaveBeenCalled() describe "for client in READY state", -> beforeEach -> @client.state = Client.STATUS_READY spyOn @client, 'write' @client.send("data") it "should call write with 0x00", -> expect(@client.write).toHaveBeenCalledWith('\x00', 'binary') it "should call write with data", -> expect(@client.write).toHaveBeenCalledWith("data", "utf8") it "should call write with 0xFF", -> expect(@client.write).toHaveBeenCalledWith('\xff', 'binary') describe "write", -> xit "should throw error if socket is not writable", -> expect(@client.write).toThrow("Client socket not writable!") it "should call socket.write if its writable", -> spyOn @client.socket, 'write' @client.write('data', 'utf8') expect(@client.socket.write).toHaveBeenCalledWith('data', 'utf8') xit "should call", -> spyOn(@client.socket, 'write').andThrow(new Error()) expect(@client.write).toThrow(new Error("Client error writing to socket")) describe "close", -> describe "when READY", -> beforeEach -> @client.state = Client.STATUS_READY it "should write empty packet", -> spyOn @client, 'write' @client.close() expect(@client.write).toHaveBeenCalledWith('\xff\x00', 'binary') describe "when not READY", -> it "should not write empty packet", -> spyOn @client, 'write' @client.close() expect(@client.write).not.toHaveBeenCalled() describe "handshake", -> beforeEach -> @http = http.createServer() @server = new Server() @server.listen(@http) @http.listen(1234) afterEach -> @http.close() @server.close() xit "should return valid handshake response", -> runs () => @ws = new WebSocket 'ws://localhost:1234' expect(@ws.readyState).toEqual 0 waits 1500 runs () => expect(@ws.readyState).toEqual 1 describe "getVersion", -> it "should return 76", -> expect(@client.getVersion()).toEqual("76") describe "getOrigin", -> it "should return request origin", -> expect(@client.getOrigin()).toEqual("localhost") describe "getLocation", -> describe "with wrong request headers", -> beforeEach -> @client.request.headers.host = null it "should return undefined", -> expect(@client.getLocation(@client.request)).toEqual(undefined) describe "with valid headers", -> it "should return valid location", -> expect(@client.getLocation(@client.request)).toEqual('ws://localhost') describe "with valid headers and port", -> beforeEach -> @client.request.headers.host = "localhost:8000" it "should return valid location with port", -> expect(@client.getLocation(@client.request)).toEqual('ws://localhost:8000') describe "with valid headers and secure socket", -> beforeEach -> @client.request.socket.secure = true it "should return location starting with wss://", -> expect(@client.getLocation(@client.request)).toEqual('wss://localhost')
55791
require './spec_helper' Client = require 'client' sys = require 'sys' net = require 'net' buffer = require 'buffer' http = require 'http' Server = require 'server' WebSocket = require('websocket-client').WebSocket describe "Client", -> beforeEach -> @socket = setTimeout: () -> setEncoding: () -> setKeepAlive: () -> on: () -> write: () -> writable: true @request = headers: 'sec-websocket-key1': ", <KEY> <KEY> U|5<KEY> . t?[T" 'sec-websocket-key2': "<KEY>" origin: "localhost" host: "localhost" socket: @socket @head = new buffer.Buffer(['\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00']) @client = new Client("", @request, @socket, @head) @client.head = @head it "should be valid", -> expect(@client).toBeDefined() describe "dataHandler", -> xit "should set status to CLOSING if data is empty", -> describe "send", -> it "should not write to socket if client is not in READY state", -> @client.state = Client.STATUS_HANDSHAKING spyOn @client, 'write' @client.send("data") expect(@client.write).not.toHaveBeenCalled() describe "for client in READY state", -> beforeEach -> @client.state = Client.STATUS_READY spyOn @client, 'write' @client.send("data") it "should call write with 0x00", -> expect(@client.write).toHaveBeenCalledWith('\x00', 'binary') it "should call write with data", -> expect(@client.write).toHaveBeenCalledWith("data", "utf8") it "should call write with 0xFF", -> expect(@client.write).toHaveBeenCalledWith('\xff', 'binary') describe "write", -> xit "should throw error if socket is not writable", -> expect(@client.write).toThrow("Client socket not writable!") it "should call socket.write if its writable", -> spyOn @client.socket, 'write' @client.write('data', 'utf8') expect(@client.socket.write).toHaveBeenCalledWith('data', 'utf8') xit "should call", -> spyOn(@client.socket, 'write').andThrow(new Error()) expect(@client.write).toThrow(new Error("Client error writing to socket")) describe "close", -> describe "when READY", -> beforeEach -> @client.state = Client.STATUS_READY it "should write empty packet", -> spyOn @client, 'write' @client.close() expect(@client.write).toHaveBeenCalledWith('\xff\x00', 'binary') describe "when not READY", -> it "should not write empty packet", -> spyOn @client, 'write' @client.close() expect(@client.write).not.toHaveBeenCalled() describe "handshake", -> beforeEach -> @http = http.createServer() @server = new Server() @server.listen(@http) @http.listen(1234) afterEach -> @http.close() @server.close() xit "should return valid handshake response", -> runs () => @ws = new WebSocket 'ws://localhost:1234' expect(@ws.readyState).toEqual 0 waits 1500 runs () => expect(@ws.readyState).toEqual 1 describe "getVersion", -> it "should return 76", -> expect(@client.getVersion()).toEqual("76") describe "getOrigin", -> it "should return request origin", -> expect(@client.getOrigin()).toEqual("localhost") describe "getLocation", -> describe "with wrong request headers", -> beforeEach -> @client.request.headers.host = null it "should return undefined", -> expect(@client.getLocation(@client.request)).toEqual(undefined) describe "with valid headers", -> it "should return valid location", -> expect(@client.getLocation(@client.request)).toEqual('ws://localhost') describe "with valid headers and port", -> beforeEach -> @client.request.headers.host = "localhost:8000" it "should return valid location with port", -> expect(@client.getLocation(@client.request)).toEqual('ws://localhost:8000') describe "with valid headers and secure socket", -> beforeEach -> @client.request.socket.secure = true it "should return location starting with wss://", -> expect(@client.getLocation(@client.request)).toEqual('wss://localhost')
true
require './spec_helper' Client = require 'client' sys = require 'sys' net = require 'net' buffer = require 'buffer' http = require 'http' Server = require 'server' WebSocket = require('websocket-client').WebSocket describe "Client", -> beforeEach -> @socket = setTimeout: () -> setEncoding: () -> setKeepAlive: () -> on: () -> write: () -> writable: true @request = headers: 'sec-websocket-key1': ", PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI U|5PI:KEY:<KEY>END_PI . t?[T" 'sec-websocket-key2': "PI:KEY:<KEY>END_PI" origin: "localhost" host: "localhost" socket: @socket @head = new buffer.Buffer(['\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00']) @client = new Client("", @request, @socket, @head) @client.head = @head it "should be valid", -> expect(@client).toBeDefined() describe "dataHandler", -> xit "should set status to CLOSING if data is empty", -> describe "send", -> it "should not write to socket if client is not in READY state", -> @client.state = Client.STATUS_HANDSHAKING spyOn @client, 'write' @client.send("data") expect(@client.write).not.toHaveBeenCalled() describe "for client in READY state", -> beforeEach -> @client.state = Client.STATUS_READY spyOn @client, 'write' @client.send("data") it "should call write with 0x00", -> expect(@client.write).toHaveBeenCalledWith('\x00', 'binary') it "should call write with data", -> expect(@client.write).toHaveBeenCalledWith("data", "utf8") it "should call write with 0xFF", -> expect(@client.write).toHaveBeenCalledWith('\xff', 'binary') describe "write", -> xit "should throw error if socket is not writable", -> expect(@client.write).toThrow("Client socket not writable!") it "should call socket.write if its writable", -> spyOn @client.socket, 'write' @client.write('data', 'utf8') expect(@client.socket.write).toHaveBeenCalledWith('data', 'utf8') xit "should call", -> spyOn(@client.socket, 'write').andThrow(new Error()) expect(@client.write).toThrow(new Error("Client error writing to socket")) describe "close", -> describe "when READY", -> beforeEach -> @client.state = Client.STATUS_READY it "should write empty packet", -> spyOn @client, 'write' @client.close() expect(@client.write).toHaveBeenCalledWith('\xff\x00', 'binary') describe "when not READY", -> it "should not write empty packet", -> spyOn @client, 'write' @client.close() expect(@client.write).not.toHaveBeenCalled() describe "handshake", -> beforeEach -> @http = http.createServer() @server = new Server() @server.listen(@http) @http.listen(1234) afterEach -> @http.close() @server.close() xit "should return valid handshake response", -> runs () => @ws = new WebSocket 'ws://localhost:1234' expect(@ws.readyState).toEqual 0 waits 1500 runs () => expect(@ws.readyState).toEqual 1 describe "getVersion", -> it "should return 76", -> expect(@client.getVersion()).toEqual("76") describe "getOrigin", -> it "should return request origin", -> expect(@client.getOrigin()).toEqual("localhost") describe "getLocation", -> describe "with wrong request headers", -> beforeEach -> @client.request.headers.host = null it "should return undefined", -> expect(@client.getLocation(@client.request)).toEqual(undefined) describe "with valid headers", -> it "should return valid location", -> expect(@client.getLocation(@client.request)).toEqual('ws://localhost') describe "with valid headers and port", -> beforeEach -> @client.request.headers.host = "localhost:8000" it "should return valid location with port", -> expect(@client.getLocation(@client.request)).toEqual('ws://localhost:8000') describe "with valid headers and secure socket", -> beforeEach -> @client.request.socket.secure = true it "should return location starting with wss://", -> expect(@client.getLocation(@client.request)).toEqual('wss://localhost')
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9987351894378662, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "ePeqZfpm\" + \"XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3\" + \"Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2k", "end": 1952, "score": 0.6055389046669006, "start": 1920, "tag": "KEY", "value": "5I2ozT5OkDlKWLJWkncJG5403HQXAkT3" }, { "context": "F1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3\" + \"Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo\" + \"AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJv", "end": 2024, "score": 0.6102381944656372, "start": 1959, "tag": "KEY", "value": "29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lo" }, { "context": "h4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo\" + \"AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsW", "end": 2090, "score": 0.6364621520042419, "start": 2033, "tag": "KEY", "value": "Wh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t" }, { "context": "YhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bh", "end": 2100, "score": 0.6716129779815674, "start": 2093, "tag": "KEY", "value": "hduTA1N" }, { "context": "o48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK", "end": 2120, "score": 0.6150387525558472, "start": 2107, "tag": "KEY", "value": "QIZR0pbHwMDat" }, { "context": "vHT1+RSQsGoC7dn2t/xjhduTA1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtN", "end": 2135, "score": 0.5825732946395874, "start": 2123, "tag": "KEY", "value": "crPqKSqGPHp1" }, { "context": "n2t/xjhduTA1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtNMhe3OZ", "end": 2141, "score": 0.609268307685852, "start": 2137, "tag": "KEY", "value": "lsWM" }, { "context": "jhduTA1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtNMhe3OZh6N95C", "end": 2147, "score": 0.5791707038879395, "start": 2142, "tag": "KEY", "value": "07ubf" }, { "context": "1N\" + \"WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtNMhe3OZh6N95CTvMX5H", "end": 2153, "score": 0.5602110028266907, "start": 2148, "tag": "KEY", "value": "bheF7" }, { "context": "WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtNMhe3OZh6N95CTvMX5HJJi4xO", "end": 2159, "score": 0.5714521408081055, "start": 2155, "tag": "KEY", "value": "Sj84" }, { "context": "pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7w", "end": 2172, "score": 0.5779705047607422, "start": 2162, "tag": "KEY", "value": "R1fYTfaK8v" }, { "context": "PHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq\" + \"qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9\"\nexpectedBase64Gzip = \"H4sIAAAAAAAAA11RS05DMQy", "end": 2247, "score": 0.6364072561264038, "start": 2181, "tag": "KEY", "value": "KBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/" }, { "context": "MX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9\"\nexpectedBase64Gzip = \"H4sIAAAAAAAAA11RS05DMQy8yh", "end": 2250, "score": 0.6840053796768188, "start": 2249, "tag": "KEY", "value": "9" }, { "context": "FE4RdpnGavKtrB5xzfO/Ll9\"\nexpectedBase64Gzip = \"H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN\" + \"496pl+mZcAotEpss7PH8c", "end": 2298, "score": 0.5788954496383667, "start": 2277, "tag": "KEY", "value": "IAAAAAAAAA11RS05DMQy8" }, { "context": "9\"\nexpectedBase64Gzip = \"H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN\" + \"496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5b", "end": 2322, "score": 0.5922237038612366, "start": 2299, "tag": "KEY", "value": "hzg6d2BPSAkJPZu4laWkjiN" }, { "context": "AAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN\" + \"496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT\" + \"cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUs", "end": 2396, "score": 0.6749987602233887, "start": 2328, "tag": "KEY", "value": "96pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT" }, { "context": "86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT\" + \"cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr\" + \"Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl", "end": 2470, "score": 0.7206249237060547, "start": 2403, "tag": "KEY", "value": "BcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr" }, { "context": "S9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr\" + \"Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G\" + \"OF25", "end": 2503, "score": 0.5603116750717163, "start": 2477, "tag": "KEY", "value": "3Uuh+gBtaHx2jjeh65iEHkQ8KN" }, { "context": "rVbM+cKEcPOxoYr\" + \"Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G\" + \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz", "end": 2543, "score": 0.5825183391571045, "start": 2505, "tag": "KEY", "value": "PNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/" }, { "context": "mjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G\" + \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPz", "end": 2560, "score": 0.506263792514801, "start": 2558, "tag": "KEY", "value": "JA" }, { "context": "Um8dPX5FJCwagLt2fa3/G\" + \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N", "end": 2574, "score": 0.5531240701675415, "start": 2573, "tag": "KEY", "value": "P" }, { "context": "8dPX5FJCwagLt2fa3/G\" + \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory", "end": 2578, "score": 0.5296626687049866, "start": 2575, "tag": "KEY", "value": "ys+" }, { "context": "CwagLt2fa3/G\" + \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory+qqp8", "end": 2583, "score": 0.5064731240272522, "start": 2582, "tag": "KEY", "value": "Y" }, { "context": "Lt2fa3/G\" + \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory+qqp8oG00yF", "end": 2589, "score": 0.5476265549659729, "start": 2586, "tag": "KEY", "value": "W+e" }, { "context": "+ \"OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory+qqp8oG00yF7c5mHo33", "end": 2597, "score": 0.56854647397995, "start": 2596, "tag": "KEY", "value": "5" }, { "context": "25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory+qqp8oG00yF7c5mHo33kJO8xf", "end": 2603, "score": 0.5415693521499634, "start": 2601, "tag": "KEY", "value": "F4" }, { "context": "U1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLj", "end": 2609, "score": 0.5640468001365662, "start": 2605, "tag": "KEY", "value": "SpKP" }, { "context": "lHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h\" + \"N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMK", "end": 2614, "score": 0.5065063834190369, "start": 2611, "tag": "KEY", "value": "GbR" } ]
test/simple/test-zlib-from-string.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test compressing and uncompressing a string with zlib common = require("../common.js") assert = require("assert") zlib = require("zlib") inputString = "ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el" + "it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la" + "cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta" + " placerat, nisi est fermentum augue, vitae gravida tellus sapien sit " + "amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss" + "e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m" + "i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar" + "cu malesuada fermentum. Nunc sed. " expectedBase64Deflate = "eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm" + "XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3" + "Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo" + "AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N" + "WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq" + "qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9" expectedBase64Gzip = "H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN" + "496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT" + "cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr" + "Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G" + "OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h" + "N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s" + "HnHNzRtagj5AQAA" zlib.deflate inputString, (err, buffer) -> assert.equal buffer.toString("base64"), expectedBase64Deflate, "deflate encoded string should match" return zlib.gzip inputString, (err, buffer) -> # Can't actually guarantee that we'll get exactly the same # deflated bytes when we compress a string, since the header # depends on stuff other than the input string itself. # However, decrypting it should definitely yield the same # result that we're expecting, and this should match what we get # from inflating the known valid deflate data. zlib.gunzip buffer, (err, gunzipped) -> assert.equal gunzipped.toString(), inputString, "Should get original string after gzip/gunzip" return return buffer = new Buffer(expectedBase64Deflate, "base64") zlib.unzip buffer, (err, buffer) -> assert.equal buffer.toString(), inputString, "decoded inflated string should match" return buffer = new Buffer(expectedBase64Gzip, "base64") zlib.unzip buffer, (err, buffer) -> assert.equal buffer.toString(), inputString, "decoded gunzipped string should match" return
37140
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test compressing and uncompressing a string with zlib common = require("../common.js") assert = require("assert") zlib = require("zlib") inputString = "ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el" + "it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la" + "cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta" + " placerat, nisi est fermentum augue, vitae gravida tellus sapien sit " + "amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss" + "e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m" + "i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar" + "cu malesuada fermentum. Nunc sed. " expectedBase64Deflate = "eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm" + "XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW<KEY>" + "Jw<KEY>fo" + "Ab<KEY>/xj<KEY>" + "Wy<KEY>nD+<KEY>vn<KEY>/<KEY>7<KEY>kq<KEY>Bm0<KEY>qq" + "qf<KEY>Ll<KEY>" expectedBase64Gzip = "H4s<KEY>y<KEY>" + "4<KEY>" + "cd<KEY>" + "Lj<KEY>wu<KEY>G" + "OF25MDU1b<KEY>hlHSlsfAwNq2c<KEY>5<KEY>opKo<KEY>8en<KEY>WxYz/Tu<KEY>t/tu<KEY>Xu<KEY>zg<KEY>HV9h" + "N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s" + "HnHNzRtagj5AQAA" zlib.deflate inputString, (err, buffer) -> assert.equal buffer.toString("base64"), expectedBase64Deflate, "deflate encoded string should match" return zlib.gzip inputString, (err, buffer) -> # Can't actually guarantee that we'll get exactly the same # deflated bytes when we compress a string, since the header # depends on stuff other than the input string itself. # However, decrypting it should definitely yield the same # result that we're expecting, and this should match what we get # from inflating the known valid deflate data. zlib.gunzip buffer, (err, gunzipped) -> assert.equal gunzipped.toString(), inputString, "Should get original string after gzip/gunzip" return return buffer = new Buffer(expectedBase64Deflate, "base64") zlib.unzip buffer, (err, buffer) -> assert.equal buffer.toString(), inputString, "decoded inflated string should match" return buffer = new Buffer(expectedBase64Gzip, "base64") zlib.unzip buffer, (err, buffer) -> assert.equal buffer.toString(), inputString, "decoded gunzipped string should match" return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test compressing and uncompressing a string with zlib common = require("../common.js") assert = require("assert") zlib = require("zlib") inputString = "ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el" + "it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la" + "cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta" + " placerat, nisi est fermentum augue, vitae gravida tellus sapien sit " + "amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss" + "e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m" + "i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar" + "cu malesuada fermentum. Nunc sed. " expectedBase64Deflate = "eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm" + "XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeWPI:KEY:<KEY>END_PI" + "JwPI:KEY:<KEY>END_PIfo" + "AbPI:KEY:<KEY>END_PI/xjPI:KEY:<KEY>END_PI" + "WyPI:KEY:<KEY>END_PInD+PI:KEY:<KEY>END_PIvnPI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIkqPI:KEY:<KEY>END_PIBm0PI:KEY:<KEY>END_PIqq" + "qfPI:KEY:<KEY>END_PILlPI:KEY:<KEY>END_PI" expectedBase64Gzip = "H4sPI:KEY:<KEY>END_PIyPI:KEY:<KEY>END_PI" + "4PI:KEY:<KEY>END_PI" + "cdPI:KEY:<KEY>END_PI" + "LjPI:KEY:<KEY>END_PIwuPI:KEY:<KEY>END_PIG" + "OF25MDU1bPI:KEY:<KEY>END_PIhlHSlsfAwNq2cPI:KEY:<KEY>END_PI5PI:KEY:<KEY>END_PIopKoPI:KEY:<KEY>END_PI8enPI:KEY:<KEY>END_PIWxYz/TuPI:KEY:<KEY>END_PIt/tuPI:KEY:<KEY>END_PIXuPI:KEY:<KEY>END_PIzgPI:KEY:<KEY>END_PIHV9h" + "N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s" + "HnHNzRtagj5AQAA" zlib.deflate inputString, (err, buffer) -> assert.equal buffer.toString("base64"), expectedBase64Deflate, "deflate encoded string should match" return zlib.gzip inputString, (err, buffer) -> # Can't actually guarantee that we'll get exactly the same # deflated bytes when we compress a string, since the header # depends on stuff other than the input string itself. # However, decrypting it should definitely yield the same # result that we're expecting, and this should match what we get # from inflating the known valid deflate data. zlib.gunzip buffer, (err, gunzipped) -> assert.equal gunzipped.toString(), inputString, "Should get original string after gzip/gunzip" return return buffer = new Buffer(expectedBase64Deflate, "base64") zlib.unzip buffer, (err, buffer) -> assert.equal buffer.toString(), inputString, "decoded inflated string should match" return buffer = new Buffer(expectedBase64Gzip, "base64") zlib.unzip buffer, (err, buffer) -> assert.equal buffer.toString(), inputString, "decoded gunzipped string should match" return
[ { "context": "able.addColumn 'mode'\n\n table.addRow ['name', 'Jane Doe', 'read']\n table.addRow ['age', 30, 'read']\n ", "end": 827, "score": 0.9997527003288269, "start": 819, "tag": "NAME", "value": "Jane Doe" } ]
spec/cursor-spec.coffee
lionel-rigoux/atom-tablr
186
require './helpers/spec-helper' {Point} = require 'atom' TableEditor = require '../lib/table-editor' Table = require '../lib/table' Selection = require '../lib/selection' Cursor = require '../lib/cursor' Range = require '../lib/range' describe 'Cursor', -> [table, displayTable, tableEditor, selection, cursor] = [] beforeEach -> atom.config.set 'tablr.tableEditor.columnWidth', 100 atom.config.set 'tablr.minimuColumnWidth', 10 atom.config.set 'tablr.tableEditor.rowHeight', 20 atom.config.set 'tablr.tableEditor.minimumRowHeight', 10 atom.config.set 'tablr.tableEditor.pageMoveRowAmount', 20 atom.config.set 'tablr.tableEditor.pageMoveColumnAmount', 20 table = new Table table.addColumn 'key' table.addColumn 'value' table.addColumn 'mode' table.addRow ['name', 'Jane Doe', 'read'] table.addRow ['age', 30, 'read'] table.addRow ['gender', 'female', 'read'] tableEditor = new TableEditor({table}) {displayTable} = tableEditor displayTable.sortBy('key') cursor = new Cursor({tableEditor, position: new Point(1,1)}) selection = new Selection({cursor, tableEditor}) describe '::moveUp', -> it 'moves the cursor up', -> cursor.moveUp() expect(cursor.position).toEqual([0,1]) it 'resets the selection range', -> cursor.moveUp() expect(selection.range).toEqual([[0,1], [1,2]]) describe 'when it goes outside the bounds', -> it 'moves to the end of the table', -> cursor.moveUp() cursor.moveUp() expect(cursor.position).toEqual([2,1]) describe '::moveDown', -> it 'moves the cursor down', -> cursor.moveDown() expect(cursor.position).toEqual([2,1]) it 'resets the selection range', -> cursor.moveDown() expect(selection.range).toEqual([[2,1], [3,2]]) describe 'when it goes outside the bounds', -> it 'moves to the beginning of the table', -> cursor.moveDown() cursor.moveDown() expect(cursor.position).toEqual([0,1]) describe '::moveLeft', -> it 'moves the cursor left', -> cursor.moveLeft() expect(cursor.position).toEqual([1,0]) it 'resets the selection range', -> cursor.moveLeft() expect(selection.range).toEqual([[1,0], [2,1]]) describe 'when it goes outside the bounds', -> it 'moves to the end of the previous row', -> cursor.moveLeft() cursor.moveLeft() expect(cursor.position).toEqual([0,2]) describe '::moveRight', -> it 'moves the cursor right', -> cursor.moveRight() expect(cursor.position).toEqual([1,2]) it 'resets the selection range', -> cursor.moveRight() expect(selection.range).toEqual([[1,2], [2,3]]) describe 'when it goes outside the bounds', -> it 'moves to the beginning of the next row', -> cursor.moveRight() cursor.moveRight() expect(cursor.position).toEqual([2,0]) describe '::moveToTop', -> it 'moves the cursor all the way to the top', -> cursor.moveToTop() expect(cursor.position).toEqual([0,1]) describe '::moveToBottom', -> it 'moves the cursor all the way to the bottom', -> cursor.moveToBottom() expect(cursor.position).toEqual([2,1]) describe '::moveToLeft', -> it 'moves the cursor all the way to the left', -> cursor.moveToLeft() expect(cursor.position).toEqual([1,0]) describe '::moveToRight', -> it 'moves the cursor all the way to the right', -> cursor.moveToRight() expect(cursor.position).toEqual([1,2]) describe 'selection moves', -> beforeEach -> table = new Table for n in [0..60] table.addColumn "column_#{n}" for r in [0..60] row = [] row.push("cell_#{r}_#{c}") for c in [0..60] table.addRow(row) tableEditor = new TableEditor({table}) {displayTable} = tableEditor cursor = new Cursor({tableEditor, position: new Point(30,30)}) selection = new Selection({ cursor, tableEditor, range: new Range([28,28],[32,32]) }) describe '::moveLeftInSelection', -> it 'moves the cursor to the left', -> cursor.moveLeftInSelection() expect(cursor.position).toEqual([30,29]) it 'does not reset the selection range', -> cursor.moveLeftInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveLeftInSelection() expect(cursor.position).toEqual([30,29]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the previous selection row', -> cursor.moveLeftInSelection() cursor.moveLeftInSelection() cursor.moveLeftInSelection() expect(cursor.position).toEqual([29,31]) it 'moves to the end of the last selection row when it goes past the first row', -> cursor.moveLeftInSelection() for n in [0..10] expect(cursor.position).toEqual([31,31]) describe '::moveRightInSelection', -> it 'moves the cursor to the right', -> cursor.moveRightInSelection() expect(cursor.position).toEqual([30,31]) it 'does not reset the selection range', -> cursor.moveRightInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveRightInSelection() expect(cursor.position).toEqual([30,31]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the previous selection row', -> cursor.moveRightInSelection() cursor.moveRightInSelection() expect(cursor.position).toEqual([31,28]) it 'moves to the end of the last selection row when it goes past the first row', -> cursor.moveRightInSelection() for n in [0..5] expect(cursor.position).toEqual([28,28]) describe '::moveUpInSelection', -> it 'moves the cursor to the top', -> cursor.moveUpInSelection() expect(cursor.position).toEqual([29,30]) it 'does not reset the selection range', -> cursor.moveUpInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveUpInSelection() expect(cursor.position).toEqual([29,30]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the selection column row', -> cursor.moveUpInSelection() cursor.moveUpInSelection() cursor.moveUpInSelection() expect(cursor.position).toEqual([31,30]) describe '::moveDownInSelection', -> it 'moves the cursor to the top', -> cursor.moveDownInSelection() expect(cursor.position).toEqual([31,30]) it 'does not reset the selection range', -> cursor.moveDownInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveDownInSelection() expect(cursor.position).toEqual([31,30]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the selection column row', -> cursor.moveDownInSelection() cursor.moveDownInSelection() expect(cursor.position).toEqual([28,30]) describe 'page moves', -> beforeEach -> table = new Table for n in [0..60] table.addColumn "column_#{n}" for r in [0..60] row = [] row.push("cell_#{r}_#{c}") for c in [0..60] table.addRow(row) tableEditor = new TableEditor({table}) {displayTable} = tableEditor cursor = new Cursor({tableEditor, position: new Point(30,30)}) selection = new Selection({cursor, tableEditor}) describe '::pageUp', -> it 'moves the cursor by the amount of page moves', -> cursor.pageUp() expect(cursor.position).toEqual([10,30]) it 'stops at the first line when going beyond top', -> cursor.pageUp() cursor.pageUp() expect(cursor.position).toEqual([0,30]) describe '::pageDown', -> it 'moves the cursor by the amount of page moves', -> cursor.pageDown() expect(cursor.position).toEqual([50,30]) it 'stops at the last line when going beyond bottom', -> cursor.pageDown() cursor.pageDown() expect(cursor.position).toEqual([60,30]) describe '::pageLeft', -> it 'moves the cursor by the amount of page moves', -> cursor.pageLeft() expect(cursor.position).toEqual([30,10]) it 'stops at the first column when going beyond left', -> cursor.pageLeft() cursor.pageLeft() expect(cursor.position).toEqual([30,0]) describe '::pageRight', -> it 'moves the cursor by the amount of page moves', -> cursor.pageRight() expect(cursor.position).toEqual([30,50]) it 'stops at the last column when going beyond right', -> cursor.pageRight() cursor.pageRight() expect(cursor.position).toEqual([30,60]) ## ######## ######## ###### ######## ####### ######## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ###### ## ## ## ######## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ## ####### ## ## ######## describe '::serialize', -> it 'serializes the cursor', -> expect(cursor.serialize()).toEqual(cursor.position.serialize())
50961
require './helpers/spec-helper' {Point} = require 'atom' TableEditor = require '../lib/table-editor' Table = require '../lib/table' Selection = require '../lib/selection' Cursor = require '../lib/cursor' Range = require '../lib/range' describe 'Cursor', -> [table, displayTable, tableEditor, selection, cursor] = [] beforeEach -> atom.config.set 'tablr.tableEditor.columnWidth', 100 atom.config.set 'tablr.minimuColumnWidth', 10 atom.config.set 'tablr.tableEditor.rowHeight', 20 atom.config.set 'tablr.tableEditor.minimumRowHeight', 10 atom.config.set 'tablr.tableEditor.pageMoveRowAmount', 20 atom.config.set 'tablr.tableEditor.pageMoveColumnAmount', 20 table = new Table table.addColumn 'key' table.addColumn 'value' table.addColumn 'mode' table.addRow ['name', '<NAME>', 'read'] table.addRow ['age', 30, 'read'] table.addRow ['gender', 'female', 'read'] tableEditor = new TableEditor({table}) {displayTable} = tableEditor displayTable.sortBy('key') cursor = new Cursor({tableEditor, position: new Point(1,1)}) selection = new Selection({cursor, tableEditor}) describe '::moveUp', -> it 'moves the cursor up', -> cursor.moveUp() expect(cursor.position).toEqual([0,1]) it 'resets the selection range', -> cursor.moveUp() expect(selection.range).toEqual([[0,1], [1,2]]) describe 'when it goes outside the bounds', -> it 'moves to the end of the table', -> cursor.moveUp() cursor.moveUp() expect(cursor.position).toEqual([2,1]) describe '::moveDown', -> it 'moves the cursor down', -> cursor.moveDown() expect(cursor.position).toEqual([2,1]) it 'resets the selection range', -> cursor.moveDown() expect(selection.range).toEqual([[2,1], [3,2]]) describe 'when it goes outside the bounds', -> it 'moves to the beginning of the table', -> cursor.moveDown() cursor.moveDown() expect(cursor.position).toEqual([0,1]) describe '::moveLeft', -> it 'moves the cursor left', -> cursor.moveLeft() expect(cursor.position).toEqual([1,0]) it 'resets the selection range', -> cursor.moveLeft() expect(selection.range).toEqual([[1,0], [2,1]]) describe 'when it goes outside the bounds', -> it 'moves to the end of the previous row', -> cursor.moveLeft() cursor.moveLeft() expect(cursor.position).toEqual([0,2]) describe '::moveRight', -> it 'moves the cursor right', -> cursor.moveRight() expect(cursor.position).toEqual([1,2]) it 'resets the selection range', -> cursor.moveRight() expect(selection.range).toEqual([[1,2], [2,3]]) describe 'when it goes outside the bounds', -> it 'moves to the beginning of the next row', -> cursor.moveRight() cursor.moveRight() expect(cursor.position).toEqual([2,0]) describe '::moveToTop', -> it 'moves the cursor all the way to the top', -> cursor.moveToTop() expect(cursor.position).toEqual([0,1]) describe '::moveToBottom', -> it 'moves the cursor all the way to the bottom', -> cursor.moveToBottom() expect(cursor.position).toEqual([2,1]) describe '::moveToLeft', -> it 'moves the cursor all the way to the left', -> cursor.moveToLeft() expect(cursor.position).toEqual([1,0]) describe '::moveToRight', -> it 'moves the cursor all the way to the right', -> cursor.moveToRight() expect(cursor.position).toEqual([1,2]) describe 'selection moves', -> beforeEach -> table = new Table for n in [0..60] table.addColumn "column_#{n}" for r in [0..60] row = [] row.push("cell_#{r}_#{c}") for c in [0..60] table.addRow(row) tableEditor = new TableEditor({table}) {displayTable} = tableEditor cursor = new Cursor({tableEditor, position: new Point(30,30)}) selection = new Selection({ cursor, tableEditor, range: new Range([28,28],[32,32]) }) describe '::moveLeftInSelection', -> it 'moves the cursor to the left', -> cursor.moveLeftInSelection() expect(cursor.position).toEqual([30,29]) it 'does not reset the selection range', -> cursor.moveLeftInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveLeftInSelection() expect(cursor.position).toEqual([30,29]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the previous selection row', -> cursor.moveLeftInSelection() cursor.moveLeftInSelection() cursor.moveLeftInSelection() expect(cursor.position).toEqual([29,31]) it 'moves to the end of the last selection row when it goes past the first row', -> cursor.moveLeftInSelection() for n in [0..10] expect(cursor.position).toEqual([31,31]) describe '::moveRightInSelection', -> it 'moves the cursor to the right', -> cursor.moveRightInSelection() expect(cursor.position).toEqual([30,31]) it 'does not reset the selection range', -> cursor.moveRightInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveRightInSelection() expect(cursor.position).toEqual([30,31]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the previous selection row', -> cursor.moveRightInSelection() cursor.moveRightInSelection() expect(cursor.position).toEqual([31,28]) it 'moves to the end of the last selection row when it goes past the first row', -> cursor.moveRightInSelection() for n in [0..5] expect(cursor.position).toEqual([28,28]) describe '::moveUpInSelection', -> it 'moves the cursor to the top', -> cursor.moveUpInSelection() expect(cursor.position).toEqual([29,30]) it 'does not reset the selection range', -> cursor.moveUpInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveUpInSelection() expect(cursor.position).toEqual([29,30]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the selection column row', -> cursor.moveUpInSelection() cursor.moveUpInSelection() cursor.moveUpInSelection() expect(cursor.position).toEqual([31,30]) describe '::moveDownInSelection', -> it 'moves the cursor to the top', -> cursor.moveDownInSelection() expect(cursor.position).toEqual([31,30]) it 'does not reset the selection range', -> cursor.moveDownInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveDownInSelection() expect(cursor.position).toEqual([31,30]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the selection column row', -> cursor.moveDownInSelection() cursor.moveDownInSelection() expect(cursor.position).toEqual([28,30]) describe 'page moves', -> beforeEach -> table = new Table for n in [0..60] table.addColumn "column_#{n}" for r in [0..60] row = [] row.push("cell_#{r}_#{c}") for c in [0..60] table.addRow(row) tableEditor = new TableEditor({table}) {displayTable} = tableEditor cursor = new Cursor({tableEditor, position: new Point(30,30)}) selection = new Selection({cursor, tableEditor}) describe '::pageUp', -> it 'moves the cursor by the amount of page moves', -> cursor.pageUp() expect(cursor.position).toEqual([10,30]) it 'stops at the first line when going beyond top', -> cursor.pageUp() cursor.pageUp() expect(cursor.position).toEqual([0,30]) describe '::pageDown', -> it 'moves the cursor by the amount of page moves', -> cursor.pageDown() expect(cursor.position).toEqual([50,30]) it 'stops at the last line when going beyond bottom', -> cursor.pageDown() cursor.pageDown() expect(cursor.position).toEqual([60,30]) describe '::pageLeft', -> it 'moves the cursor by the amount of page moves', -> cursor.pageLeft() expect(cursor.position).toEqual([30,10]) it 'stops at the first column when going beyond left', -> cursor.pageLeft() cursor.pageLeft() expect(cursor.position).toEqual([30,0]) describe '::pageRight', -> it 'moves the cursor by the amount of page moves', -> cursor.pageRight() expect(cursor.position).toEqual([30,50]) it 'stops at the last column when going beyond right', -> cursor.pageRight() cursor.pageRight() expect(cursor.position).toEqual([30,60]) ## ######## ######## ###### ######## ####### ######## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ###### ## ## ## ######## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ## ####### ## ## ######## describe '::serialize', -> it 'serializes the cursor', -> expect(cursor.serialize()).toEqual(cursor.position.serialize())
true
require './helpers/spec-helper' {Point} = require 'atom' TableEditor = require '../lib/table-editor' Table = require '../lib/table' Selection = require '../lib/selection' Cursor = require '../lib/cursor' Range = require '../lib/range' describe 'Cursor', -> [table, displayTable, tableEditor, selection, cursor] = [] beforeEach -> atom.config.set 'tablr.tableEditor.columnWidth', 100 atom.config.set 'tablr.minimuColumnWidth', 10 atom.config.set 'tablr.tableEditor.rowHeight', 20 atom.config.set 'tablr.tableEditor.minimumRowHeight', 10 atom.config.set 'tablr.tableEditor.pageMoveRowAmount', 20 atom.config.set 'tablr.tableEditor.pageMoveColumnAmount', 20 table = new Table table.addColumn 'key' table.addColumn 'value' table.addColumn 'mode' table.addRow ['name', 'PI:NAME:<NAME>END_PI', 'read'] table.addRow ['age', 30, 'read'] table.addRow ['gender', 'female', 'read'] tableEditor = new TableEditor({table}) {displayTable} = tableEditor displayTable.sortBy('key') cursor = new Cursor({tableEditor, position: new Point(1,1)}) selection = new Selection({cursor, tableEditor}) describe '::moveUp', -> it 'moves the cursor up', -> cursor.moveUp() expect(cursor.position).toEqual([0,1]) it 'resets the selection range', -> cursor.moveUp() expect(selection.range).toEqual([[0,1], [1,2]]) describe 'when it goes outside the bounds', -> it 'moves to the end of the table', -> cursor.moveUp() cursor.moveUp() expect(cursor.position).toEqual([2,1]) describe '::moveDown', -> it 'moves the cursor down', -> cursor.moveDown() expect(cursor.position).toEqual([2,1]) it 'resets the selection range', -> cursor.moveDown() expect(selection.range).toEqual([[2,1], [3,2]]) describe 'when it goes outside the bounds', -> it 'moves to the beginning of the table', -> cursor.moveDown() cursor.moveDown() expect(cursor.position).toEqual([0,1]) describe '::moveLeft', -> it 'moves the cursor left', -> cursor.moveLeft() expect(cursor.position).toEqual([1,0]) it 'resets the selection range', -> cursor.moveLeft() expect(selection.range).toEqual([[1,0], [2,1]]) describe 'when it goes outside the bounds', -> it 'moves to the end of the previous row', -> cursor.moveLeft() cursor.moveLeft() expect(cursor.position).toEqual([0,2]) describe '::moveRight', -> it 'moves the cursor right', -> cursor.moveRight() expect(cursor.position).toEqual([1,2]) it 'resets the selection range', -> cursor.moveRight() expect(selection.range).toEqual([[1,2], [2,3]]) describe 'when it goes outside the bounds', -> it 'moves to the beginning of the next row', -> cursor.moveRight() cursor.moveRight() expect(cursor.position).toEqual([2,0]) describe '::moveToTop', -> it 'moves the cursor all the way to the top', -> cursor.moveToTop() expect(cursor.position).toEqual([0,1]) describe '::moveToBottom', -> it 'moves the cursor all the way to the bottom', -> cursor.moveToBottom() expect(cursor.position).toEqual([2,1]) describe '::moveToLeft', -> it 'moves the cursor all the way to the left', -> cursor.moveToLeft() expect(cursor.position).toEqual([1,0]) describe '::moveToRight', -> it 'moves the cursor all the way to the right', -> cursor.moveToRight() expect(cursor.position).toEqual([1,2]) describe 'selection moves', -> beforeEach -> table = new Table for n in [0..60] table.addColumn "column_#{n}" for r in [0..60] row = [] row.push("cell_#{r}_#{c}") for c in [0..60] table.addRow(row) tableEditor = new TableEditor({table}) {displayTable} = tableEditor cursor = new Cursor({tableEditor, position: new Point(30,30)}) selection = new Selection({ cursor, tableEditor, range: new Range([28,28],[32,32]) }) describe '::moveLeftInSelection', -> it 'moves the cursor to the left', -> cursor.moveLeftInSelection() expect(cursor.position).toEqual([30,29]) it 'does not reset the selection range', -> cursor.moveLeftInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveLeftInSelection() expect(cursor.position).toEqual([30,29]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the previous selection row', -> cursor.moveLeftInSelection() cursor.moveLeftInSelection() cursor.moveLeftInSelection() expect(cursor.position).toEqual([29,31]) it 'moves to the end of the last selection row when it goes past the first row', -> cursor.moveLeftInSelection() for n in [0..10] expect(cursor.position).toEqual([31,31]) describe '::moveRightInSelection', -> it 'moves the cursor to the right', -> cursor.moveRightInSelection() expect(cursor.position).toEqual([30,31]) it 'does not reset the selection range', -> cursor.moveRightInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveRightInSelection() expect(cursor.position).toEqual([30,31]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the previous selection row', -> cursor.moveRightInSelection() cursor.moveRightInSelection() expect(cursor.position).toEqual([31,28]) it 'moves to the end of the last selection row when it goes past the first row', -> cursor.moveRightInSelection() for n in [0..5] expect(cursor.position).toEqual([28,28]) describe '::moveUpInSelection', -> it 'moves the cursor to the top', -> cursor.moveUpInSelection() expect(cursor.position).toEqual([29,30]) it 'does not reset the selection range', -> cursor.moveUpInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveUpInSelection() expect(cursor.position).toEqual([29,30]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the selection column row', -> cursor.moveUpInSelection() cursor.moveUpInSelection() cursor.moveUpInSelection() expect(cursor.position).toEqual([31,30]) describe '::moveDownInSelection', -> it 'moves the cursor to the top', -> cursor.moveDownInSelection() expect(cursor.position).toEqual([31,30]) it 'does not reset the selection range', -> cursor.moveDownInSelection() expect(selection.range).toEqual([[28,28], [32,32]]) describe 'when the selection spans only the cursor cell', -> beforeEach -> selection.resetRangeOnCursor() it 'ignores the selection bounds', -> cursor.moveDownInSelection() expect(cursor.position).toEqual([31,30]) describe 'when it goes outside the selection bounds', -> it 'moves to the end of the selection column row', -> cursor.moveDownInSelection() cursor.moveDownInSelection() expect(cursor.position).toEqual([28,30]) describe 'page moves', -> beforeEach -> table = new Table for n in [0..60] table.addColumn "column_#{n}" for r in [0..60] row = [] row.push("cell_#{r}_#{c}") for c in [0..60] table.addRow(row) tableEditor = new TableEditor({table}) {displayTable} = tableEditor cursor = new Cursor({tableEditor, position: new Point(30,30)}) selection = new Selection({cursor, tableEditor}) describe '::pageUp', -> it 'moves the cursor by the amount of page moves', -> cursor.pageUp() expect(cursor.position).toEqual([10,30]) it 'stops at the first line when going beyond top', -> cursor.pageUp() cursor.pageUp() expect(cursor.position).toEqual([0,30]) describe '::pageDown', -> it 'moves the cursor by the amount of page moves', -> cursor.pageDown() expect(cursor.position).toEqual([50,30]) it 'stops at the last line when going beyond bottom', -> cursor.pageDown() cursor.pageDown() expect(cursor.position).toEqual([60,30]) describe '::pageLeft', -> it 'moves the cursor by the amount of page moves', -> cursor.pageLeft() expect(cursor.position).toEqual([30,10]) it 'stops at the first column when going beyond left', -> cursor.pageLeft() cursor.pageLeft() expect(cursor.position).toEqual([30,0]) describe '::pageRight', -> it 'moves the cursor by the amount of page moves', -> cursor.pageRight() expect(cursor.position).toEqual([30,50]) it 'stops at the last column when going beyond right', -> cursor.pageRight() cursor.pageRight() expect(cursor.position).toEqual([30,60]) ## ######## ######## ###### ######## ####### ######## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ###### ## ## ## ######## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ## ####### ## ## ######## describe '::serialize', -> it 'serializes the cursor', -> expect(cursor.serialize()).toEqual(cursor.position.serialize())
[ { "context": " return true\n if token == 'group:__world__'\n return true\n if token", "end": 660, "score": 0.5730932950973511, "start": 655, "tag": "KEY", "value": "world" }, { "context": " return true\n if token == 'group:__authenticated__' and this.user?\n return true\n\n ", "end": 736, "score": 0.5771263241767883, "start": 715, "tag": "KEY", "value": "group:__authenticated" } ]
h/js/services.coffee
gergely-ujvari/h
0
class Hypothesis extends Annotator events: serviceDiscovery: 'serviceDiscovery' # Plugin configuration options: noMatching: true Discovery: {} Heatmap: {} Permissions: permissions: read: ['group:__world__'] userAuthorize: (action, annotation, user) -> if annotation.permissions tokens = annotation.permissions[action] || [] if tokens.length == 0 # Empty or missing tokens array: only admin can perform action. return false for token in tokens if this.userId(user) == token return true if token == 'group:__world__' return true if token == 'group:__authenticated__' and this.user? return true # No tokens matched: action should not be performed. return false # Coarse-grained authorization else if annotation.user return user and this.userId(user) == this.userId(annotation.user) # No authorization info on annotation: free-for-all! true showEditPermissionsCheckbox: false, showViewPermissionsCheckbox: false, userString: (user) -> user.replace(/^acct:(.+)@(.+)$/, '$1 on $2') Threading: {} Document: {} # Internal state dragging: false # * To enable dragging only when we really want to ongoing_edit: false # * Is there an interrupted edit by login # Here as a noop just to make the Permissions plugin happy # XXX: Change me when Annotator stops assuming things about viewers viewer: addField: (-> ) this.$inject = ['$document', '$location', '$rootScope', '$route', 'drafts'] constructor: ($document, $location, $rootScope, $route, drafts) -> super ($document.find 'body') # Load plugins for own name, opts of @options if not @plugins[name] and name of Annotator.Plugin this.addPlugin(name, opts) # Set up XDM connection this._setupXDM() # Add some info to new annotations this.subscribe 'beforeAnnotationCreated', (annotation) => # Annotator assumes a valid array of targets and highlights. unless annotation.target? annotation.target = [] unless annotation.highlights? annotation.highlights = [] # Register it with the draft service drafts.add annotation # Set default owner permissions on all annotations for event in ['beforeAnnotationCreated', 'beforeAnnotationUpdated'] this.subscribe event, (annotation) => permissions = @plugins.Permissions if permissions.user? userId = permissions.options.userId(permissions.user) for action, roles of annotation.permissions unless userId in roles then roles.push userId # Update the heatmap when the host is updated or annotations are loaded bridge = @plugins.Bridge heatmap = @plugins.Heatmap threading = @threading updateOn = [ 'hostUpdated' 'annotationsLoaded' 'annotationCreated' 'annotationDeleted' ] for event in updateOn this.subscribe event, => @provider.call method: 'getHighlights' success: ({highlights, offset}) -> heatmap.updateHeatmap highlights: for hl in highlights when hl.data annotation = bridge.cache[hl.data] angular.extend hl, data: annotation offset: offset # Reload the route after annotations are loaded this.subscribe 'annotationsLoaded', -> $route.reload() _setupXDM: -> $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' $window = @element.injector().get '$window' drafts = @element.injector().get 'drafts' # Set up the bridge plugin, which bridges the main annotation methods # between the host page and the panel widget. whitelist = ['diffHTML', 'quote', 'ranges', 'target', 'id'] this.addPlugin 'Bridge', origin: $location.search().xdm window: $window.parent formatter: (annotation) => formatted = {} for k, v of annotation when k in whitelist formatted[k] = v formatted parser: (annotation) => parsed = {} for k, v of annotation when k in whitelist parsed[k] = v parsed @api = Channel.build origin: $location.search().xdm scope: 'annotator:api' window: $window.parent .bind('addToken', (ctx, token) => @element.scope().token = token @element.scope().$digest() ) @provider = Channel.build origin: $location.search().xdm scope: 'annotator:panel' window: $window.parent onReady: => console.log "Sidepanel: channel is ready" # Dodge toolbars [DISABLE] #@provider.getMaxBottom (max) => # @element.css('margin-top', "#{max}px") # @element.find('.topbar').css("top", "#{max}px") # @element.find('#gutter').css("margin-top", "#{max}px") # @plugins.Heatmap.BUCKET_THRESHOLD_PAD += max @provider .bind('publish', (ctx, args...) => this.publish args...) .bind('back', => # This guy does stuff when you "back out" of the interface. # (Currently triggered by a click on the source page.) return unless drafts.discard() $rootScope.$apply => this.hide() ) _setupWrapper: -> @wrapper = @element.find('#wrapper') .on 'mousewheel', (event, delta) -> # prevent overscroll from scrolling host frame # This is actually a bit tricky. Starting from the event target and # working up the DOM tree, find an element which is scrollable # and has a scrollHeight larger than its clientHeight. # I've obsered that some styles, such as :before content, may increase # scrollHeight of non-scrollable elements, and that there a mysterious # discrepancy of 1px sometimes occurs that invalidates the equation # typically cited for determining when scrolling has reached bottom: # (scrollHeight - scrollTop == clientHeight) $current = $(event.target) while $current.css('overflow') in ['hidden', 'visible'] $parent = $current.parent() # Break out on document nodes if $parent.get(0).nodeType == 9 event.preventDefault() return $current = $parent scrollTop = $current[0].scrollTop scrollEnd = $current[0].scrollHeight - $current[0].clientHeight if delta > 0 and scrollTop == 0 event.preventDefault() else if delta < 0 and scrollEnd - scrollTop <= 5 event.preventDefault() this _setupDocumentEvents: -> el = document.createElementNS 'http://www.w3.org/1999/xhtml', 'canvas' el.width = el.height = 1 @element.append el handle = @element.find('.topbar .tri')[0] handle.addEventListener 'dragstart', (event) => event.dataTransfer.setData 'text/plain', '' event.dataTransfer.setDragImage el, 0, 0 @dragging = true @provider.notify method: 'setDrag', params: true @provider.notify method: 'dragFrame', params: event.screenX handle.addEventListener 'dragend', (event) => @dragging = false @provider.notify method: 'setDrag', params: false @provider.notify method: 'dragFrame', params: event.screenX @element[0].addEventListener 'dragover', (event) => if @dragging then @provider.notify method: 'dragFrame', params: event.screenX @element[0].addEventListener 'dragleave', (event) => if @dragging then @provider.notify method: 'dragFrame', params: event.screenX this # Override things not used in the angular version. _setupDynamicStyle: -> this _setupViewer: -> this _setupEditor: -> this # (Optionally) put some HTML formatting around a quote getHtmlQuote: (quote) -> quote # Do nothing in the app frame, let the host handle it. setupAnnotation: (annotation) -> annotation showViewer: (annotations=[]) => this.show() @element.injector().invoke [ '$location', '$rootScope', ($location, $rootScope) -> $rootScope.annotations = annotations $location.path('/viewer').replace() $rootScope.$digest() ] this clickAdder: => @provider.notify method: 'adderClick' showEditor: (annotation) => this.show() @element.injector().invoke [ '$location', '$rootScope', '$route' ($location, $rootScope, $route) => unless this.plugins.Auth? and this.plugins.Auth.haveValidToken() $route.current.locals.$scope.$apply -> $route.current.locals.$scope.$emit 'showAuth', true @provider.notify method: 'onEditorHide' @ongoing_edit = true return # Set the path search = id: annotation.id action: 'create' $location.path('/editor').search(search) # Digest the change $rootScope.$digest() @ongoing_edit = false # Push the annotation into the editor scope if $route.current.controller is 'EditorController' $route.current.locals.$scope.$apply (s) -> s.annotation = annotation ] this show: => @element.scope().frame.visible = true hide: => @element.scope().frame.visible = false patch_store: (store) => $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' # When the store plugin finishes a request, update the annotation # using a monkey-patched update function which updates the threading # if the annotation has a newly-assigned id and ensures that the id # is enumerable. store.updateAnnotation = (annotation, data) => if annotation.id? and annotation.id != data.id # Update the id table for the threading thread = @threading.getContainer annotation.id thread.id = data.id @threading.idTable[data.id] = thread delete @threading.idTable[annotation.id] # The id is no longer temporary and should be serialized # on future Store requests. Object.defineProperty annotation, 'id', configurable: true enumerable: true writable: true # If the annotation is loaded in a view, switch the view # to reference the new id. search = $location.search() if search? and search.id == annotation.id search.id = data.id $location.search(search).replace() # Update the annotation with the new data annotation = angular.extend annotation, data # Give angular a chance to react $rootScope.$digest() serviceDiscovery: (options) => $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' angular.extend @options, Store: options # Get the location of the annotated document @provider.call method: 'getDocumentInfo' success: (info) => href = info.uri @plugins.Document.metadata = info.metadata options = angular.extend {}, (@options.Store or {}), annotationData: uri: href loadFromSearch: limit: 1000 uri: href this.addStore(options) addStore: (options) -> this.addPlugin 'Store', options this.patch_store this.plugins.Store href = options.loadFromSearch?.uri return unless href? console.log "Loaded annotions for '" + href + "'." for uri in @plugins.Document.uris() console.log "Also loading annotations for: " + uri this.plugins.Store.loadAnnotationsFromSearch uri: uri class AuthenticationProvider constructor: -> @actions = load: method: 'GET' withCredentials: true for action in ['login', 'logout', 'register', 'forgot', 'activate'] @actions[action] = method: 'POST' params: '__formid__': action withCredentials: true @actions['claim'] = @actions['forgot'] $get: [ '$document', '$resource', ($document, $resource) -> baseUrl = $document[0].baseURI.replace(/:(\d+)/, '\\:$1') $resource(baseUrl, {}, @actions).load()] class DraftProvider drafts: [] $get: -> this add: (draft) -> @drafts.push draft unless this.contains draft remove: (draft) -> @drafts = (d for d in @drafts when d isnt draft) contains: (draft) -> (@drafts.indexOf draft) != -1 discard: -> count = (d for d in @drafts when d.text?.length).length text = switch count when 0 then null when 1 """You have an unsaved reply. Do you really want to discard this draft?""" else """You have #{count} unsaved replies. Do you really want to discard these drafts?""" if count == 0 or confirm text @drafts = [] true else false class FlashProvider queues: '': [] info: [] error: [] success: [] notice: null timeout: null this.$inject = ['$httpProvider'] constructor: ($httpProvider) -> # Configure notification classes angular.extend Annotator.Notification, INFO: 'info' ERROR: 'error' SUCCESS: 'success' # Configure the response interceptor $httpProvider.responseInterceptors.push ['$q', ($q) => (promise) => promise.then (response) => data = response.data format = response.headers 'content-type' if format?.match /^application\/json/ if data.flash? this._flash q, msgs for q, msgs of data.flash if data.status is 'failure' this._flash 'error', data.reason $q.reject(data.reason) else if data.status is 'okay' response.data = data.model response else response ] _process: -> @timeout = null for q, msgs of @queues if msgs.length msg = msgs.shift() unless q then [q, msg] = msg notice = Annotator.showNotification msg, q @timeout = this._wait => # work around Annotator.Notification not removing classes for _, klass of notice.options.classes notice.element.removeClass klass this._process() break $get: ['$timeout', 'annotator', ($timeout, annotator) -> this._wait = (cb) -> $timeout cb, 5000 angular.bind this, this._flash ] _flash: (queue, messages) -> if @queues[queue]? @queues[queue] = @queues[queue]?.concat messages this._process() unless @timeout? angular.module('h.services', ['ngResource']) .provider('authentication', AuthenticationProvider) .provider('drafts', DraftProvider) .provider('flash', FlashProvider) .service('annotator', Hypothesis)
102612
class Hypothesis extends Annotator events: serviceDiscovery: 'serviceDiscovery' # Plugin configuration options: noMatching: true Discovery: {} Heatmap: {} Permissions: permissions: read: ['group:__world__'] userAuthorize: (action, annotation, user) -> if annotation.permissions tokens = annotation.permissions[action] || [] if tokens.length == 0 # Empty or missing tokens array: only admin can perform action. return false for token in tokens if this.userId(user) == token return true if token == 'group:__<KEY>__' return true if token == '<KEY>__' and this.user? return true # No tokens matched: action should not be performed. return false # Coarse-grained authorization else if annotation.user return user and this.userId(user) == this.userId(annotation.user) # No authorization info on annotation: free-for-all! true showEditPermissionsCheckbox: false, showViewPermissionsCheckbox: false, userString: (user) -> user.replace(/^acct:(.+)@(.+)$/, '$1 on $2') Threading: {} Document: {} # Internal state dragging: false # * To enable dragging only when we really want to ongoing_edit: false # * Is there an interrupted edit by login # Here as a noop just to make the Permissions plugin happy # XXX: Change me when Annotator stops assuming things about viewers viewer: addField: (-> ) this.$inject = ['$document', '$location', '$rootScope', '$route', 'drafts'] constructor: ($document, $location, $rootScope, $route, drafts) -> super ($document.find 'body') # Load plugins for own name, opts of @options if not @plugins[name] and name of Annotator.Plugin this.addPlugin(name, opts) # Set up XDM connection this._setupXDM() # Add some info to new annotations this.subscribe 'beforeAnnotationCreated', (annotation) => # Annotator assumes a valid array of targets and highlights. unless annotation.target? annotation.target = [] unless annotation.highlights? annotation.highlights = [] # Register it with the draft service drafts.add annotation # Set default owner permissions on all annotations for event in ['beforeAnnotationCreated', 'beforeAnnotationUpdated'] this.subscribe event, (annotation) => permissions = @plugins.Permissions if permissions.user? userId = permissions.options.userId(permissions.user) for action, roles of annotation.permissions unless userId in roles then roles.push userId # Update the heatmap when the host is updated or annotations are loaded bridge = @plugins.Bridge heatmap = @plugins.Heatmap threading = @threading updateOn = [ 'hostUpdated' 'annotationsLoaded' 'annotationCreated' 'annotationDeleted' ] for event in updateOn this.subscribe event, => @provider.call method: 'getHighlights' success: ({highlights, offset}) -> heatmap.updateHeatmap highlights: for hl in highlights when hl.data annotation = bridge.cache[hl.data] angular.extend hl, data: annotation offset: offset # Reload the route after annotations are loaded this.subscribe 'annotationsLoaded', -> $route.reload() _setupXDM: -> $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' $window = @element.injector().get '$window' drafts = @element.injector().get 'drafts' # Set up the bridge plugin, which bridges the main annotation methods # between the host page and the panel widget. whitelist = ['diffHTML', 'quote', 'ranges', 'target', 'id'] this.addPlugin 'Bridge', origin: $location.search().xdm window: $window.parent formatter: (annotation) => formatted = {} for k, v of annotation when k in whitelist formatted[k] = v formatted parser: (annotation) => parsed = {} for k, v of annotation when k in whitelist parsed[k] = v parsed @api = Channel.build origin: $location.search().xdm scope: 'annotator:api' window: $window.parent .bind('addToken', (ctx, token) => @element.scope().token = token @element.scope().$digest() ) @provider = Channel.build origin: $location.search().xdm scope: 'annotator:panel' window: $window.parent onReady: => console.log "Sidepanel: channel is ready" # Dodge toolbars [DISABLE] #@provider.getMaxBottom (max) => # @element.css('margin-top', "#{max}px") # @element.find('.topbar').css("top", "#{max}px") # @element.find('#gutter').css("margin-top", "#{max}px") # @plugins.Heatmap.BUCKET_THRESHOLD_PAD += max @provider .bind('publish', (ctx, args...) => this.publish args...) .bind('back', => # This guy does stuff when you "back out" of the interface. # (Currently triggered by a click on the source page.) return unless drafts.discard() $rootScope.$apply => this.hide() ) _setupWrapper: -> @wrapper = @element.find('#wrapper') .on 'mousewheel', (event, delta) -> # prevent overscroll from scrolling host frame # This is actually a bit tricky. Starting from the event target and # working up the DOM tree, find an element which is scrollable # and has a scrollHeight larger than its clientHeight. # I've obsered that some styles, such as :before content, may increase # scrollHeight of non-scrollable elements, and that there a mysterious # discrepancy of 1px sometimes occurs that invalidates the equation # typically cited for determining when scrolling has reached bottom: # (scrollHeight - scrollTop == clientHeight) $current = $(event.target) while $current.css('overflow') in ['hidden', 'visible'] $parent = $current.parent() # Break out on document nodes if $parent.get(0).nodeType == 9 event.preventDefault() return $current = $parent scrollTop = $current[0].scrollTop scrollEnd = $current[0].scrollHeight - $current[0].clientHeight if delta > 0 and scrollTop == 0 event.preventDefault() else if delta < 0 and scrollEnd - scrollTop <= 5 event.preventDefault() this _setupDocumentEvents: -> el = document.createElementNS 'http://www.w3.org/1999/xhtml', 'canvas' el.width = el.height = 1 @element.append el handle = @element.find('.topbar .tri')[0] handle.addEventListener 'dragstart', (event) => event.dataTransfer.setData 'text/plain', '' event.dataTransfer.setDragImage el, 0, 0 @dragging = true @provider.notify method: 'setDrag', params: true @provider.notify method: 'dragFrame', params: event.screenX handle.addEventListener 'dragend', (event) => @dragging = false @provider.notify method: 'setDrag', params: false @provider.notify method: 'dragFrame', params: event.screenX @element[0].addEventListener 'dragover', (event) => if @dragging then @provider.notify method: 'dragFrame', params: event.screenX @element[0].addEventListener 'dragleave', (event) => if @dragging then @provider.notify method: 'dragFrame', params: event.screenX this # Override things not used in the angular version. _setupDynamicStyle: -> this _setupViewer: -> this _setupEditor: -> this # (Optionally) put some HTML formatting around a quote getHtmlQuote: (quote) -> quote # Do nothing in the app frame, let the host handle it. setupAnnotation: (annotation) -> annotation showViewer: (annotations=[]) => this.show() @element.injector().invoke [ '$location', '$rootScope', ($location, $rootScope) -> $rootScope.annotations = annotations $location.path('/viewer').replace() $rootScope.$digest() ] this clickAdder: => @provider.notify method: 'adderClick' showEditor: (annotation) => this.show() @element.injector().invoke [ '$location', '$rootScope', '$route' ($location, $rootScope, $route) => unless this.plugins.Auth? and this.plugins.Auth.haveValidToken() $route.current.locals.$scope.$apply -> $route.current.locals.$scope.$emit 'showAuth', true @provider.notify method: 'onEditorHide' @ongoing_edit = true return # Set the path search = id: annotation.id action: 'create' $location.path('/editor').search(search) # Digest the change $rootScope.$digest() @ongoing_edit = false # Push the annotation into the editor scope if $route.current.controller is 'EditorController' $route.current.locals.$scope.$apply (s) -> s.annotation = annotation ] this show: => @element.scope().frame.visible = true hide: => @element.scope().frame.visible = false patch_store: (store) => $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' # When the store plugin finishes a request, update the annotation # using a monkey-patched update function which updates the threading # if the annotation has a newly-assigned id and ensures that the id # is enumerable. store.updateAnnotation = (annotation, data) => if annotation.id? and annotation.id != data.id # Update the id table for the threading thread = @threading.getContainer annotation.id thread.id = data.id @threading.idTable[data.id] = thread delete @threading.idTable[annotation.id] # The id is no longer temporary and should be serialized # on future Store requests. Object.defineProperty annotation, 'id', configurable: true enumerable: true writable: true # If the annotation is loaded in a view, switch the view # to reference the new id. search = $location.search() if search? and search.id == annotation.id search.id = data.id $location.search(search).replace() # Update the annotation with the new data annotation = angular.extend annotation, data # Give angular a chance to react $rootScope.$digest() serviceDiscovery: (options) => $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' angular.extend @options, Store: options # Get the location of the annotated document @provider.call method: 'getDocumentInfo' success: (info) => href = info.uri @plugins.Document.metadata = info.metadata options = angular.extend {}, (@options.Store or {}), annotationData: uri: href loadFromSearch: limit: 1000 uri: href this.addStore(options) addStore: (options) -> this.addPlugin 'Store', options this.patch_store this.plugins.Store href = options.loadFromSearch?.uri return unless href? console.log "Loaded annotions for '" + href + "'." for uri in @plugins.Document.uris() console.log "Also loading annotations for: " + uri this.plugins.Store.loadAnnotationsFromSearch uri: uri class AuthenticationProvider constructor: -> @actions = load: method: 'GET' withCredentials: true for action in ['login', 'logout', 'register', 'forgot', 'activate'] @actions[action] = method: 'POST' params: '__formid__': action withCredentials: true @actions['claim'] = @actions['forgot'] $get: [ '$document', '$resource', ($document, $resource) -> baseUrl = $document[0].baseURI.replace(/:(\d+)/, '\\:$1') $resource(baseUrl, {}, @actions).load()] class DraftProvider drafts: [] $get: -> this add: (draft) -> @drafts.push draft unless this.contains draft remove: (draft) -> @drafts = (d for d in @drafts when d isnt draft) contains: (draft) -> (@drafts.indexOf draft) != -1 discard: -> count = (d for d in @drafts when d.text?.length).length text = switch count when 0 then null when 1 """You have an unsaved reply. Do you really want to discard this draft?""" else """You have #{count} unsaved replies. Do you really want to discard these drafts?""" if count == 0 or confirm text @drafts = [] true else false class FlashProvider queues: '': [] info: [] error: [] success: [] notice: null timeout: null this.$inject = ['$httpProvider'] constructor: ($httpProvider) -> # Configure notification classes angular.extend Annotator.Notification, INFO: 'info' ERROR: 'error' SUCCESS: 'success' # Configure the response interceptor $httpProvider.responseInterceptors.push ['$q', ($q) => (promise) => promise.then (response) => data = response.data format = response.headers 'content-type' if format?.match /^application\/json/ if data.flash? this._flash q, msgs for q, msgs of data.flash if data.status is 'failure' this._flash 'error', data.reason $q.reject(data.reason) else if data.status is 'okay' response.data = data.model response else response ] _process: -> @timeout = null for q, msgs of @queues if msgs.length msg = msgs.shift() unless q then [q, msg] = msg notice = Annotator.showNotification msg, q @timeout = this._wait => # work around Annotator.Notification not removing classes for _, klass of notice.options.classes notice.element.removeClass klass this._process() break $get: ['$timeout', 'annotator', ($timeout, annotator) -> this._wait = (cb) -> $timeout cb, 5000 angular.bind this, this._flash ] _flash: (queue, messages) -> if @queues[queue]? @queues[queue] = @queues[queue]?.concat messages this._process() unless @timeout? angular.module('h.services', ['ngResource']) .provider('authentication', AuthenticationProvider) .provider('drafts', DraftProvider) .provider('flash', FlashProvider) .service('annotator', Hypothesis)
true
class Hypothesis extends Annotator events: serviceDiscovery: 'serviceDiscovery' # Plugin configuration options: noMatching: true Discovery: {} Heatmap: {} Permissions: permissions: read: ['group:__world__'] userAuthorize: (action, annotation, user) -> if annotation.permissions tokens = annotation.permissions[action] || [] if tokens.length == 0 # Empty or missing tokens array: only admin can perform action. return false for token in tokens if this.userId(user) == token return true if token == 'group:__PI:KEY:<KEY>END_PI__' return true if token == 'PI:KEY:<KEY>END_PI__' and this.user? return true # No tokens matched: action should not be performed. return false # Coarse-grained authorization else if annotation.user return user and this.userId(user) == this.userId(annotation.user) # No authorization info on annotation: free-for-all! true showEditPermissionsCheckbox: false, showViewPermissionsCheckbox: false, userString: (user) -> user.replace(/^acct:(.+)@(.+)$/, '$1 on $2') Threading: {} Document: {} # Internal state dragging: false # * To enable dragging only when we really want to ongoing_edit: false # * Is there an interrupted edit by login # Here as a noop just to make the Permissions plugin happy # XXX: Change me when Annotator stops assuming things about viewers viewer: addField: (-> ) this.$inject = ['$document', '$location', '$rootScope', '$route', 'drafts'] constructor: ($document, $location, $rootScope, $route, drafts) -> super ($document.find 'body') # Load plugins for own name, opts of @options if not @plugins[name] and name of Annotator.Plugin this.addPlugin(name, opts) # Set up XDM connection this._setupXDM() # Add some info to new annotations this.subscribe 'beforeAnnotationCreated', (annotation) => # Annotator assumes a valid array of targets and highlights. unless annotation.target? annotation.target = [] unless annotation.highlights? annotation.highlights = [] # Register it with the draft service drafts.add annotation # Set default owner permissions on all annotations for event in ['beforeAnnotationCreated', 'beforeAnnotationUpdated'] this.subscribe event, (annotation) => permissions = @plugins.Permissions if permissions.user? userId = permissions.options.userId(permissions.user) for action, roles of annotation.permissions unless userId in roles then roles.push userId # Update the heatmap when the host is updated or annotations are loaded bridge = @plugins.Bridge heatmap = @plugins.Heatmap threading = @threading updateOn = [ 'hostUpdated' 'annotationsLoaded' 'annotationCreated' 'annotationDeleted' ] for event in updateOn this.subscribe event, => @provider.call method: 'getHighlights' success: ({highlights, offset}) -> heatmap.updateHeatmap highlights: for hl in highlights when hl.data annotation = bridge.cache[hl.data] angular.extend hl, data: annotation offset: offset # Reload the route after annotations are loaded this.subscribe 'annotationsLoaded', -> $route.reload() _setupXDM: -> $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' $window = @element.injector().get '$window' drafts = @element.injector().get 'drafts' # Set up the bridge plugin, which bridges the main annotation methods # between the host page and the panel widget. whitelist = ['diffHTML', 'quote', 'ranges', 'target', 'id'] this.addPlugin 'Bridge', origin: $location.search().xdm window: $window.parent formatter: (annotation) => formatted = {} for k, v of annotation when k in whitelist formatted[k] = v formatted parser: (annotation) => parsed = {} for k, v of annotation when k in whitelist parsed[k] = v parsed @api = Channel.build origin: $location.search().xdm scope: 'annotator:api' window: $window.parent .bind('addToken', (ctx, token) => @element.scope().token = token @element.scope().$digest() ) @provider = Channel.build origin: $location.search().xdm scope: 'annotator:panel' window: $window.parent onReady: => console.log "Sidepanel: channel is ready" # Dodge toolbars [DISABLE] #@provider.getMaxBottom (max) => # @element.css('margin-top', "#{max}px") # @element.find('.topbar').css("top", "#{max}px") # @element.find('#gutter').css("margin-top", "#{max}px") # @plugins.Heatmap.BUCKET_THRESHOLD_PAD += max @provider .bind('publish', (ctx, args...) => this.publish args...) .bind('back', => # This guy does stuff when you "back out" of the interface. # (Currently triggered by a click on the source page.) return unless drafts.discard() $rootScope.$apply => this.hide() ) _setupWrapper: -> @wrapper = @element.find('#wrapper') .on 'mousewheel', (event, delta) -> # prevent overscroll from scrolling host frame # This is actually a bit tricky. Starting from the event target and # working up the DOM tree, find an element which is scrollable # and has a scrollHeight larger than its clientHeight. # I've obsered that some styles, such as :before content, may increase # scrollHeight of non-scrollable elements, and that there a mysterious # discrepancy of 1px sometimes occurs that invalidates the equation # typically cited for determining when scrolling has reached bottom: # (scrollHeight - scrollTop == clientHeight) $current = $(event.target) while $current.css('overflow') in ['hidden', 'visible'] $parent = $current.parent() # Break out on document nodes if $parent.get(0).nodeType == 9 event.preventDefault() return $current = $parent scrollTop = $current[0].scrollTop scrollEnd = $current[0].scrollHeight - $current[0].clientHeight if delta > 0 and scrollTop == 0 event.preventDefault() else if delta < 0 and scrollEnd - scrollTop <= 5 event.preventDefault() this _setupDocumentEvents: -> el = document.createElementNS 'http://www.w3.org/1999/xhtml', 'canvas' el.width = el.height = 1 @element.append el handle = @element.find('.topbar .tri')[0] handle.addEventListener 'dragstart', (event) => event.dataTransfer.setData 'text/plain', '' event.dataTransfer.setDragImage el, 0, 0 @dragging = true @provider.notify method: 'setDrag', params: true @provider.notify method: 'dragFrame', params: event.screenX handle.addEventListener 'dragend', (event) => @dragging = false @provider.notify method: 'setDrag', params: false @provider.notify method: 'dragFrame', params: event.screenX @element[0].addEventListener 'dragover', (event) => if @dragging then @provider.notify method: 'dragFrame', params: event.screenX @element[0].addEventListener 'dragleave', (event) => if @dragging then @provider.notify method: 'dragFrame', params: event.screenX this # Override things not used in the angular version. _setupDynamicStyle: -> this _setupViewer: -> this _setupEditor: -> this # (Optionally) put some HTML formatting around a quote getHtmlQuote: (quote) -> quote # Do nothing in the app frame, let the host handle it. setupAnnotation: (annotation) -> annotation showViewer: (annotations=[]) => this.show() @element.injector().invoke [ '$location', '$rootScope', ($location, $rootScope) -> $rootScope.annotations = annotations $location.path('/viewer').replace() $rootScope.$digest() ] this clickAdder: => @provider.notify method: 'adderClick' showEditor: (annotation) => this.show() @element.injector().invoke [ '$location', '$rootScope', '$route' ($location, $rootScope, $route) => unless this.plugins.Auth? and this.plugins.Auth.haveValidToken() $route.current.locals.$scope.$apply -> $route.current.locals.$scope.$emit 'showAuth', true @provider.notify method: 'onEditorHide' @ongoing_edit = true return # Set the path search = id: annotation.id action: 'create' $location.path('/editor').search(search) # Digest the change $rootScope.$digest() @ongoing_edit = false # Push the annotation into the editor scope if $route.current.controller is 'EditorController' $route.current.locals.$scope.$apply (s) -> s.annotation = annotation ] this show: => @element.scope().frame.visible = true hide: => @element.scope().frame.visible = false patch_store: (store) => $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' # When the store plugin finishes a request, update the annotation # using a monkey-patched update function which updates the threading # if the annotation has a newly-assigned id and ensures that the id # is enumerable. store.updateAnnotation = (annotation, data) => if annotation.id? and annotation.id != data.id # Update the id table for the threading thread = @threading.getContainer annotation.id thread.id = data.id @threading.idTable[data.id] = thread delete @threading.idTable[annotation.id] # The id is no longer temporary and should be serialized # on future Store requests. Object.defineProperty annotation, 'id', configurable: true enumerable: true writable: true # If the annotation is loaded in a view, switch the view # to reference the new id. search = $location.search() if search? and search.id == annotation.id search.id = data.id $location.search(search).replace() # Update the annotation with the new data annotation = angular.extend annotation, data # Give angular a chance to react $rootScope.$digest() serviceDiscovery: (options) => $location = @element.injector().get '$location' $rootScope = @element.injector().get '$rootScope' angular.extend @options, Store: options # Get the location of the annotated document @provider.call method: 'getDocumentInfo' success: (info) => href = info.uri @plugins.Document.metadata = info.metadata options = angular.extend {}, (@options.Store or {}), annotationData: uri: href loadFromSearch: limit: 1000 uri: href this.addStore(options) addStore: (options) -> this.addPlugin 'Store', options this.patch_store this.plugins.Store href = options.loadFromSearch?.uri return unless href? console.log "Loaded annotions for '" + href + "'." for uri in @plugins.Document.uris() console.log "Also loading annotations for: " + uri this.plugins.Store.loadAnnotationsFromSearch uri: uri class AuthenticationProvider constructor: -> @actions = load: method: 'GET' withCredentials: true for action in ['login', 'logout', 'register', 'forgot', 'activate'] @actions[action] = method: 'POST' params: '__formid__': action withCredentials: true @actions['claim'] = @actions['forgot'] $get: [ '$document', '$resource', ($document, $resource) -> baseUrl = $document[0].baseURI.replace(/:(\d+)/, '\\:$1') $resource(baseUrl, {}, @actions).load()] class DraftProvider drafts: [] $get: -> this add: (draft) -> @drafts.push draft unless this.contains draft remove: (draft) -> @drafts = (d for d in @drafts when d isnt draft) contains: (draft) -> (@drafts.indexOf draft) != -1 discard: -> count = (d for d in @drafts when d.text?.length).length text = switch count when 0 then null when 1 """You have an unsaved reply. Do you really want to discard this draft?""" else """You have #{count} unsaved replies. Do you really want to discard these drafts?""" if count == 0 or confirm text @drafts = [] true else false class FlashProvider queues: '': [] info: [] error: [] success: [] notice: null timeout: null this.$inject = ['$httpProvider'] constructor: ($httpProvider) -> # Configure notification classes angular.extend Annotator.Notification, INFO: 'info' ERROR: 'error' SUCCESS: 'success' # Configure the response interceptor $httpProvider.responseInterceptors.push ['$q', ($q) => (promise) => promise.then (response) => data = response.data format = response.headers 'content-type' if format?.match /^application\/json/ if data.flash? this._flash q, msgs for q, msgs of data.flash if data.status is 'failure' this._flash 'error', data.reason $q.reject(data.reason) else if data.status is 'okay' response.data = data.model response else response ] _process: -> @timeout = null for q, msgs of @queues if msgs.length msg = msgs.shift() unless q then [q, msg] = msg notice = Annotator.showNotification msg, q @timeout = this._wait => # work around Annotator.Notification not removing classes for _, klass of notice.options.classes notice.element.removeClass klass this._process() break $get: ['$timeout', 'annotator', ($timeout, annotator) -> this._wait = (cb) -> $timeout cb, 5000 angular.bind this, this._flash ] _flash: (queue, messages) -> if @queues[queue]? @queues[queue] = @queues[queue]?.concat messages this._process() unless @timeout? angular.module('h.services', ['ngResource']) .provider('authentication', AuthenticationProvider) .provider('drafts', DraftProvider) .provider('flash', FlashProvider) .service('annotator', Hypothesis)
[ { "context": "ling.\n#\n# URI parsing logic taken from parseUri by Steven Levithan:\n#\n# http://stevenlevithan.com/demo/parseuri/js/\n", "end": 118, "score": 0.9997349381446838, "start": 103, "tag": "NAME", "value": "Steven Levithan" }, { "context": "ery logic taken from Rack:\n#\n# https://github.com/rack/rack/blob/master/lib/rack/utils.rb\nclass Batman.U", "end": 235, "score": 0.9975652694702148, "start": 231, "tag": "USERNAME", "value": "rack" }, { "context": " @relative(),\n ].join(\"\")\n\n userInfo: ->\n [@user, \":#{@password}\" if @password].join(\"\")\n\n author", "end": 1157, "score": 0.9988003373146057, "start": 1151, "tag": "USERNAME", "value": "[@user" } ]
src/utilities/uri.coffee
davidcornu/batman
1
# A lightweight URI class for parsing and param juggling. # # URI parsing logic taken from parseUri by Steven Levithan: # # http://stevenlevithan.com/demo/parseuri/js/ # # Nested query logic taken from Rack: # # https://github.com/rack/rack/blob/master/lib/rack/utils.rb class Batman.URI ### # URI parsing ### strictParser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ attributes = ["source","protocol","authority","userInfo","user","password","hostname","port","relative","path","directory","file","query","hash"] constructor: (str) -> matches = strictParser.exec(str) i = 14 while (i--) @[attributes[i]] = matches[i] or '' @queryParams = @constructor.paramsFromQuery(@query) delete @authority delete @userInfo delete @relative delete @directory delete @file delete @query queryString: -> @constructor.queryFromParams(@queryParams) toString: -> [ "#{@protocol}:" if @protocol, "//" if @authority(), @authority(), @relative(), ].join("") userInfo: -> [@user, ":#{@password}" if @password].join("") authority: -> [@userInfo(), "@" if @user or @password, @hostname, ":#{@port}" if @port].join("") relative: -> query = @queryString() [@path, "?#{query}" if query, "##{@hash}" if @hash].join("") directory: -> splitPath = @path.split('/') if splitPath.length > 1 splitPath.slice(0, splitPath.length - 1).join('/') + "/" else "" file: -> splitPath = @path.split("/") splitPath[splitPath.length - 1] ### # query parsing ### @paramsFromQuery: (query) -> params = {} for segment in query.split('&') if matches = segment.match(keyVal) normalizeParams(params, decodeQueryComponent(matches[1]), decodeQueryComponent(matches[2])) else normalizeParams(params, decodeQueryComponent(segment), null) params @decodeQueryComponent: decodeQueryComponent = (str) -> decodeURIComponent(str.replace(plus, '%20')) nameParser = /^[\[\]]*([^\[\]]+)\]*(.*)/ childKeyMatchers = [/^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/] plus = /\+/g r20 = /%20/g keyVal = /^([^=]*)=(.*)/ normalizeParams = (params, name, v) -> if matches = name.match(nameParser) k = matches[1] after = matches[2] else return if after is '' params[k] = v else if after is '[]' params[k] ?= [] throw new Error("expected Array (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Array' params[k].push(v) else if matches = (after.match(childKeyMatchers[0]) or after.match(childKeyMatchers[1])) childKey = matches[1] params[k] ?= [] throw new Error("expected Array (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Array' last = params[k][params[k].length-1] if Batman.typeOf(last) is 'Object' and not (childKey of last) normalizeParams(last, childKey, v) else params[k].push(normalizeParams({}, childKey, v)) else params[k] ?= {} throw new Error("expected Object (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Object' params[k] = normalizeParams(params[k], after, v) params ### # query building ### @queryFromParams: queryFromParams = (value, prefix) -> return prefix unless value? valueType = Batman.typeOf(value) unless prefix? or valueType is 'Object' throw new Error("value must be an Object") switch valueType when 'Array' (arrayResults = [] if (value.length == 0) arrayResults.push queryFromParams(null, "#{prefix}[]") else arrayResults.push queryFromParams(v, "#{prefix}[]") for v in value arrayResults).join("&") when 'Object' (queryFromParams(v, if prefix then "#{prefix}[#{encodeQueryComponent(k)}]" else encodeQueryComponent(k)) for k, v of value).join("&") else if prefix? "#{prefix}=#{encodeQueryComponent(value)}" else encodeQueryComponent(value) @encodeComponent: encodeComponent = (str) -> if str? encodeURIComponent(str) else '' @encodeQueryComponent: encodeQueryComponent = (str) -> encodeComponent(str).replace(r20, '+')
153821
# A lightweight URI class for parsing and param juggling. # # URI parsing logic taken from parseUri by <NAME>: # # http://stevenlevithan.com/demo/parseuri/js/ # # Nested query logic taken from Rack: # # https://github.com/rack/rack/blob/master/lib/rack/utils.rb class Batman.URI ### # URI parsing ### strictParser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ attributes = ["source","protocol","authority","userInfo","user","password","hostname","port","relative","path","directory","file","query","hash"] constructor: (str) -> matches = strictParser.exec(str) i = 14 while (i--) @[attributes[i]] = matches[i] or '' @queryParams = @constructor.paramsFromQuery(@query) delete @authority delete @userInfo delete @relative delete @directory delete @file delete @query queryString: -> @constructor.queryFromParams(@queryParams) toString: -> [ "#{@protocol}:" if @protocol, "//" if @authority(), @authority(), @relative(), ].join("") userInfo: -> [@user, ":#{@password}" if @password].join("") authority: -> [@userInfo(), "@" if @user or @password, @hostname, ":#{@port}" if @port].join("") relative: -> query = @queryString() [@path, "?#{query}" if query, "##{@hash}" if @hash].join("") directory: -> splitPath = @path.split('/') if splitPath.length > 1 splitPath.slice(0, splitPath.length - 1).join('/') + "/" else "" file: -> splitPath = @path.split("/") splitPath[splitPath.length - 1] ### # query parsing ### @paramsFromQuery: (query) -> params = {} for segment in query.split('&') if matches = segment.match(keyVal) normalizeParams(params, decodeQueryComponent(matches[1]), decodeQueryComponent(matches[2])) else normalizeParams(params, decodeQueryComponent(segment), null) params @decodeQueryComponent: decodeQueryComponent = (str) -> decodeURIComponent(str.replace(plus, '%20')) nameParser = /^[\[\]]*([^\[\]]+)\]*(.*)/ childKeyMatchers = [/^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/] plus = /\+/g r20 = /%20/g keyVal = /^([^=]*)=(.*)/ normalizeParams = (params, name, v) -> if matches = name.match(nameParser) k = matches[1] after = matches[2] else return if after is '' params[k] = v else if after is '[]' params[k] ?= [] throw new Error("expected Array (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Array' params[k].push(v) else if matches = (after.match(childKeyMatchers[0]) or after.match(childKeyMatchers[1])) childKey = matches[1] params[k] ?= [] throw new Error("expected Array (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Array' last = params[k][params[k].length-1] if Batman.typeOf(last) is 'Object' and not (childKey of last) normalizeParams(last, childKey, v) else params[k].push(normalizeParams({}, childKey, v)) else params[k] ?= {} throw new Error("expected Object (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Object' params[k] = normalizeParams(params[k], after, v) params ### # query building ### @queryFromParams: queryFromParams = (value, prefix) -> return prefix unless value? valueType = Batman.typeOf(value) unless prefix? or valueType is 'Object' throw new Error("value must be an Object") switch valueType when 'Array' (arrayResults = [] if (value.length == 0) arrayResults.push queryFromParams(null, "#{prefix}[]") else arrayResults.push queryFromParams(v, "#{prefix}[]") for v in value arrayResults).join("&") when 'Object' (queryFromParams(v, if prefix then "#{prefix}[#{encodeQueryComponent(k)}]" else encodeQueryComponent(k)) for k, v of value).join("&") else if prefix? "#{prefix}=#{encodeQueryComponent(value)}" else encodeQueryComponent(value) @encodeComponent: encodeComponent = (str) -> if str? encodeURIComponent(str) else '' @encodeQueryComponent: encodeQueryComponent = (str) -> encodeComponent(str).replace(r20, '+')
true
# A lightweight URI class for parsing and param juggling. # # URI parsing logic taken from parseUri by PI:NAME:<NAME>END_PI: # # http://stevenlevithan.com/demo/parseuri/js/ # # Nested query logic taken from Rack: # # https://github.com/rack/rack/blob/master/lib/rack/utils.rb class Batman.URI ### # URI parsing ### strictParser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ attributes = ["source","protocol","authority","userInfo","user","password","hostname","port","relative","path","directory","file","query","hash"] constructor: (str) -> matches = strictParser.exec(str) i = 14 while (i--) @[attributes[i]] = matches[i] or '' @queryParams = @constructor.paramsFromQuery(@query) delete @authority delete @userInfo delete @relative delete @directory delete @file delete @query queryString: -> @constructor.queryFromParams(@queryParams) toString: -> [ "#{@protocol}:" if @protocol, "//" if @authority(), @authority(), @relative(), ].join("") userInfo: -> [@user, ":#{@password}" if @password].join("") authority: -> [@userInfo(), "@" if @user or @password, @hostname, ":#{@port}" if @port].join("") relative: -> query = @queryString() [@path, "?#{query}" if query, "##{@hash}" if @hash].join("") directory: -> splitPath = @path.split('/') if splitPath.length > 1 splitPath.slice(0, splitPath.length - 1).join('/') + "/" else "" file: -> splitPath = @path.split("/") splitPath[splitPath.length - 1] ### # query parsing ### @paramsFromQuery: (query) -> params = {} for segment in query.split('&') if matches = segment.match(keyVal) normalizeParams(params, decodeQueryComponent(matches[1]), decodeQueryComponent(matches[2])) else normalizeParams(params, decodeQueryComponent(segment), null) params @decodeQueryComponent: decodeQueryComponent = (str) -> decodeURIComponent(str.replace(plus, '%20')) nameParser = /^[\[\]]*([^\[\]]+)\]*(.*)/ childKeyMatchers = [/^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/] plus = /\+/g r20 = /%20/g keyVal = /^([^=]*)=(.*)/ normalizeParams = (params, name, v) -> if matches = name.match(nameParser) k = matches[1] after = matches[2] else return if after is '' params[k] = v else if after is '[]' params[k] ?= [] throw new Error("expected Array (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Array' params[k].push(v) else if matches = (after.match(childKeyMatchers[0]) or after.match(childKeyMatchers[1])) childKey = matches[1] params[k] ?= [] throw new Error("expected Array (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Array' last = params[k][params[k].length-1] if Batman.typeOf(last) is 'Object' and not (childKey of last) normalizeParams(last, childKey, v) else params[k].push(normalizeParams({}, childKey, v)) else params[k] ?= {} throw new Error("expected Object (got #{Batman.typeOf(params[k])}) for param \"#{k}\"") unless Batman.typeOf(params[k]) is 'Object' params[k] = normalizeParams(params[k], after, v) params ### # query building ### @queryFromParams: queryFromParams = (value, prefix) -> return prefix unless value? valueType = Batman.typeOf(value) unless prefix? or valueType is 'Object' throw new Error("value must be an Object") switch valueType when 'Array' (arrayResults = [] if (value.length == 0) arrayResults.push queryFromParams(null, "#{prefix}[]") else arrayResults.push queryFromParams(v, "#{prefix}[]") for v in value arrayResults).join("&") when 'Object' (queryFromParams(v, if prefix then "#{prefix}[#{encodeQueryComponent(k)}]" else encodeQueryComponent(k)) for k, v of value).join("&") else if prefix? "#{prefix}=#{encodeQueryComponent(value)}" else encodeQueryComponent(value) @encodeComponent: encodeComponent = (str) -> if str? encodeURIComponent(str) else '' @encodeQueryComponent: encodeQueryComponent = (str) -> encodeComponent(str).replace(r20, '+')
[ { "context": "6b2a17b9\",\n \"latestCommit\": \"07d4a9749a09d4891b82fcb55bc1883f6b2a17b9\",\n \"repository\": {\n ", "end": 612, "score": 0.4726472795009613, "start": 607, "tag": "PASSWORD", "value": "891b8" }, { "context": ",\n \"latestCommit\": \"07d4a9749a09d4891b82fcb55bc1883f6b2a17b9\",\n \"repository\": {\n \"slug\": \"b2", "end": 633, "score": 0.5086662769317627, "start": 616, "tag": "PASSWORD", "value": "55bc1883f6b2a17b9" }, { "context": "\n \"project\": {\n \"key\": \"LEARN\",\n \"id\": 185,\n \"nam", "end": 946, "score": 0.9819968938827515, "start": 941, "tag": "KEY", "value": "LEARN" }, { "context": "\n \"project\": {\n \"key\": \"LEARN\",\n \"id\": 185,\n \"nam", "end": 2850, "score": 0.5928506851196289, "start": 2845, "tag": "KEY", "value": "LEARN" }, { "context": "author\": {\n \"user\": {\n \"name\": \"mfu\",\n \"emailAddress\": \"minchao.fu@blackbo", "end": 4301, "score": 0.9996649026870728, "start": 4298, "tag": "USERNAME", "value": "mfu" }, { "context": " \"name\": \"mfu\",\n \"emailAddress\": \"minchao.fu@blackboard.com\",\n \"id\": 6255,\n \"displayNam", "end": 4358, "score": 0.9999288320541382, "start": 4333, "tag": "EMAIL", "value": "minchao.fu@blackboard.com" }, { "context": " \"id\": 6255,\n \"displayName\": \"Minchao Fu\",\n \"active\": true,\n \"slug\":", "end": 4423, "score": 0.9998186826705933, "start": 4413, "tag": "NAME", "value": "Minchao Fu" }, { "context": "144ec8fbe866ed7e82a827\",\n \"latestCommit\": \"e61cfb1d6659d5738e144ec8fbe866ed7e82a827\",\n \"repository\": {\n ", "end": 5828, "score": 0.6925253868103027, "start": 5809, "tag": "PASSWORD", "value": "e61cfb1d6659d5738e1" }, { "context": "7\",\n \"latestCommit\": \"e61cfb1d6659d5738e144ec8fbe866ed7e82a827\",\n \"repository\": {\n ", "end": 5832, "score": 0.5239298343658447, "start": 5830, "tag": "PASSWORD", "value": "ec" }, { "context": "\n \"latestCommit\": \"e61cfb1d6659d5738e144ec8fbe866ed7e82a827\",\n \"repository\": {\n ", "end": 5836, "score": 0.5544654726982117, "start": 5833, "tag": "PASSWORD", "value": "fbe" }, { "context": " \"latestCommit\": \"e61cfb1d6659d5738e144ec8fbe866ed7e82a827\",\n \"repository\": {\n \"sl", "end": 5841, "score": 0.5080937743186951, "start": 5839, "tag": "PASSWORD", "value": "ed" }, { "context": "atestCommit\": \"e61cfb1d6659d5738e144ec8fbe866ed7e82a827\",\n \"repository\": {\n \"slug\": \"ap", "end": 5849, "score": 0.5904446840286255, "start": 5844, "tag": "PASSWORD", "value": "2a827" }, { "context": "\n \"project\": {\n \"key\": \"LEARN\",\n \"id\": 185,\n \"nam", "end": 6162, "score": 0.9862295389175415, "start": 6157, "tag": "KEY", "value": "LEARN" }, { "context": "\n \"project\": {\n \"key\": \"LEARN\",\n \"id\": 185,\n \"nam", "end": 8066, "score": 0.6934729814529419, "start": 8061, "tag": "KEY", "value": "LEARN" }, { "context": "author\": {\n \"user\": {\n \"name\": \"mfu\",\n \"emailAddress\": \"minchao.fu@blackbo", "end": 9517, "score": 0.999609649181366, "start": 9514, "tag": "USERNAME", "value": "mfu" }, { "context": " \"name\": \"mfu\",\n \"emailAddress\": \"minchao.fu@blackboard.com\",\n \"id\": 6255,\n \"displayNam", "end": 9574, "score": 0.9999284744262695, "start": 9549, "tag": "EMAIL", "value": "minchao.fu@blackboard.com" }, { "context": " \"id\": 6255,\n \"displayName\": \"Minchao Fu\",\n \"active\": true,\n \"slug\":", "end": 9639, "score": 0.9998323321342468, "start": 9629, "tag": "NAME", "value": "Minchao Fu" }, { "context": "ewers\": [{\n \"user\": {\n \"name\": \"jima\",\n \"emailAddress\": \"jianguo.ma@blackbo", "end": 10180, "score": 0.9996334314346313, "start": 10176, "tag": "USERNAME", "value": "jima" }, { "context": " \"name\": \"jima\",\n \"emailAddress\": \"jianguo.ma@blackboard.com\",\n \"id\": 6354,\n \"displayNam", "end": 10237, "score": 0.9999318718910217, "start": 10212, "tag": "EMAIL", "value": "jianguo.ma@blackboard.com" }, { "context": " \"id\": 6354,\n \"displayName\": \"Jianguo Ma\",\n \"active\": true,\n \"slug\":", "end": 10302, "score": 0.9998337626457214, "start": 10292, "tag": "NAME", "value": "Jianguo Ma" }, { "context": " \"id\": 185,\n \"name\": \"learn\",\n \"description\": \"Projects relate", "end": 13974, "score": 0.6552445888519287, "start": 13969, "tag": "NAME", "value": "learn" }, { "context": "author\": {\n \"user\": {\n \"name\": \"mfu\",\n \"emailAddress\": \"minchao.fu@blackbo", "end": 15335, "score": 0.9997352957725525, "start": 15332, "tag": "USERNAME", "value": "mfu" }, { "context": " \"name\": \"mfu\",\n \"emailAddress\": \"minchao.fu@blackboard.com\",\n \"id\": 6255,\n \"displayNam", "end": 15392, "score": 0.9999319314956665, "start": 15367, "tag": "EMAIL", "value": "minchao.fu@blackboard.com" }, { "context": " \"id\": 6255,\n \"displayName\": \"Minchao Fu\",\n \"active\": true,\n \"slug\":", "end": 15457, "score": 0.9998029470443726, "start": 15447, "tag": "NAME", "value": "Minchao Fu" }, { "context": "ewers\": [{\n \"user\": {\n \"name\": \"jima\",\n \"emailAddress\": \"jianguo.ma@blackbo", "end": 15998, "score": 0.9995124340057373, "start": 15994, "tag": "USERNAME", "value": "jima" }, { "context": " \"name\": \"jima\",\n \"emailAddress\": \"jianguo.ma@blackboard.com\",\n \"id\": 6354,\n \"displayNam", "end": 16055, "score": 0.9999254941940308, "start": 16030, "tag": "EMAIL", "value": "jianguo.ma@blackboard.com" }, { "context": " \"id\": 6354,\n \"displayName\": \"Jianguo Ma\",\n \"active\": true,\n \"slug\":", "end": 16120, "score": 0.9998713731765747, "start": 16110, "tag": "NAME", "value": "Jianguo Ma" } ]
offline/rest/inbox/latest/pull-requests.cson
fuminchao/atlassian-stash-reviewboard
0
"size": 3, "limit": 10, "isLastPage": true, "values": [{ "id": 88, "version": 0, "title": "Feature/ULTRA-11163 patch goal alignments to assessment question", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456117898790, "updatedDate": 1456117898790, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments-to-assessment-question", "displayId": "feature/ULTRA-11163-patch-goal-alignments-to-assessment-question", "latestChangeset": "07d4a9749a09d4891b82fcb55bc1883f6b2a17b9", "latestCommit": "07d4a9749a09d4891b82fcb55bc1883f6b2a17b9", "repository": { "slug": "b2-assessment", "id": 4856, "name": "b2-assessment", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-assessment/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-assessment.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "64855a8fa223006c10ff8801e28534cee8395d19", "latestCommit": "64855a8fa223006c10ff8801e28534cee8395d19", "repository": { "slug": "b2-assessment", "id": 4856, "name": "b2-assessment", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-assessment/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-assessment.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "minchao.fu@blackboard.com", "id": 6255, "displayName": "Minchao Fu", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/b2-assessment/pull-requests/88", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/pull-requests/88" }] } }, { "id": 8, "version": 0, "title": "ULTRA-11163-patch-goal-alignments", "description": "Renaming the parameter", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456108362134, "updatedDate": 1456108362134, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments", "displayId": "feature/ULTRA-11163-patch-goal-alignments", "latestChangeset": "e61cfb1d6659d5738e144ec8fbe866ed7e82a827", "latestCommit": "e61cfb1d6659d5738e144ec8fbe866ed7e82a827", "repository": { "slug": "apis-goal-api", "id": 4815, "name": "apis-goal-api", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/apis-goal-api/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "links": { "clone": [{ "href": "ssh://git@stash.bbpd.io/learn/apis-goal-api.git", "name": "ssh" }, { "href": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "name": "http" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "4d3b2c2130281a942b9532fe32d09b2ec3b76456", "latestCommit": "4d3b2c2130281a942b9532fe32d09b2ec3b76456", "repository": { "slug": "apis-goal-api", "id": 4815, "name": "apis-goal-api", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/apis-goal-api/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "links": { "clone": [{ "href": "ssh://git@stash.bbpd.io/learn/apis-goal-api.git", "name": "ssh" }, { "href": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "name": "http" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "minchao.fu@blackboard.com", "id": 6255, "displayName": "Minchao Fu", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [{ "user": { "name": "jima", "emailAddress": "jianguo.ma@blackboard.com", "id": 6354, "displayName": "Jianguo Ma", "active": true, "slug": "jima", "type": "NORMAL", "link": { "url": "/users/jima", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/jima" }] }, "avatarUrl": "https://secure.gravatar.com/avatar/0bfb0100e67c62eda7eaf3763b760d05.jpg?s=64&d=mm" }, "role": "REVIEWER", "approved": false }], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/apis-goal-api/pull-requests/8", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/pull-requests/8" }] } }, { "id": 14, "version": 0, "title": "ULTRA-11163-patch-goal-alignments", "description": "Renaming the parameter", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456108338039, "updatedDate": 1456108338039, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments", "displayId": "feature/ULTRA-11163-patch-goal-alignments", "latestChangeset": "d05ceefeed509d12101de4c43e97ed6d0c2d51a3", "latestCommit": "d05ceefeed509d12101de4c43e97ed6d0c2d51a3", "repository": { "slug": "b2-goal", "id": 4912, "name": "b2-goal", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-goal/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-goal.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "210ff66855824b80413286b660314a78669b918b", "latestCommit": "210ff66855824b80413286b660314a78669b918b", "repository": { "slug": "b2-goal", "id": 4912, "name": "b2-goal", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-goal/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-goal.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "minchao.fu@blackboard.com", "id": 6255, "displayName": "Minchao Fu", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [{ "user": { "name": "jima", "emailAddress": "jianguo.ma@blackboard.com", "id": 6354, "displayName": "Jianguo Ma", "active": true, "slug": "jima", "type": "NORMAL", "link": { "url": "/users/jima", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/jima" }] }, "avatarUrl": "https://secure.gravatar.com/avatar/0bfb0100e67c62eda7eaf3763b760d05.jpg?s=64&d=mm" }, "role": "REVIEWER", "approved": false }], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/b2-goal/pull-requests/14", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/pull-requests/14" }] } }], "start": 0
130755
"size": 3, "limit": 10, "isLastPage": true, "values": [{ "id": 88, "version": 0, "title": "Feature/ULTRA-11163 patch goal alignments to assessment question", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456117898790, "updatedDate": 1456117898790, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments-to-assessment-question", "displayId": "feature/ULTRA-11163-patch-goal-alignments-to-assessment-question", "latestChangeset": "07d4a9749a09d4891b82fcb55bc1883f6b2a17b9", "latestCommit": "07d4a9749a09d4<PASSWORD>2fcb<PASSWORD>", "repository": { "slug": "b2-assessment", "id": 4856, "name": "b2-assessment", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "<KEY>", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-assessment/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-assessment.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "64855a8fa223006c10ff8801e28534cee8395d19", "latestCommit": "64855a8fa223006c10ff8801e28534cee8395d19", "repository": { "slug": "b2-assessment", "id": 4856, "name": "b2-assessment", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "<KEY>", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-assessment/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-assessment.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "<EMAIL>", "id": 6255, "displayName": "<NAME>", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/b2-assessment/pull-requests/88", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/pull-requests/88" }] } }, { "id": 8, "version": 0, "title": "ULTRA-11163-patch-goal-alignments", "description": "Renaming the parameter", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456108362134, "updatedDate": 1456108362134, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments", "displayId": "feature/ULTRA-11163-patch-goal-alignments", "latestChangeset": "e61cfb1d6659d5738e144ec8fbe866ed7e82a827", "latestCommit": "<PASSWORD>44<PASSWORD>8<PASSWORD>866<PASSWORD>7e8<PASSWORD>", "repository": { "slug": "apis-goal-api", "id": 4815, "name": "apis-goal-api", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "<KEY>", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/apis-goal-api/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "links": { "clone": [{ "href": "ssh://git@stash.bbpd.io/learn/apis-goal-api.git", "name": "ssh" }, { "href": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "name": "http" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "4d3b2c2130281a942b9532fe32d09b2ec3b76456", "latestCommit": "4d3b2c2130281a942b9532fe32d09b2ec3b76456", "repository": { "slug": "apis-goal-api", "id": 4815, "name": "apis-goal-api", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "<KEY>", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/apis-goal-api/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "links": { "clone": [{ "href": "ssh://git@stash.bbpd.io/learn/apis-goal-api.git", "name": "ssh" }, { "href": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "name": "http" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "<EMAIL>", "id": 6255, "displayName": "<NAME>", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [{ "user": { "name": "jima", "emailAddress": "<EMAIL>", "id": 6354, "displayName": "<NAME>", "active": true, "slug": "jima", "type": "NORMAL", "link": { "url": "/users/jima", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/jima" }] }, "avatarUrl": "https://secure.gravatar.com/avatar/0bfb0100e67c62eda7eaf3763b760d05.jpg?s=64&d=mm" }, "role": "REVIEWER", "approved": false }], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/apis-goal-api/pull-requests/8", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/pull-requests/8" }] } }, { "id": 14, "version": 0, "title": "ULTRA-11163-patch-goal-alignments", "description": "Renaming the parameter", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456108338039, "updatedDate": 1456108338039, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments", "displayId": "feature/ULTRA-11163-patch-goal-alignments", "latestChangeset": "d05ceefeed509d12101de4c43e97ed6d0c2d51a3", "latestCommit": "d05ceefeed509d12101de4c43e97ed6d0c2d51a3", "repository": { "slug": "b2-goal", "id": 4912, "name": "b2-goal", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-goal/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-goal.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "210ff66855824b80413286b660314a78669b918b", "latestCommit": "210ff66855824b80413286b660314a78669b918b", "repository": { "slug": "b2-goal", "id": 4912, "name": "b2-goal", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "<NAME>", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-goal/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-goal.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "<EMAIL>", "id": 6255, "displayName": "<NAME>", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [{ "user": { "name": "jima", "emailAddress": "<EMAIL>", "id": 6354, "displayName": "<NAME>", "active": true, "slug": "jima", "type": "NORMAL", "link": { "url": "/users/jima", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/jima" }] }, "avatarUrl": "https://secure.gravatar.com/avatar/0bfb0100e67c62eda7eaf3763b760d05.jpg?s=64&d=mm" }, "role": "REVIEWER", "approved": false }], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/b2-goal/pull-requests/14", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/pull-requests/14" }] } }], "start": 0
true
"size": 3, "limit": 10, "isLastPage": true, "values": [{ "id": 88, "version": 0, "title": "Feature/ULTRA-11163 patch goal alignments to assessment question", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456117898790, "updatedDate": 1456117898790, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments-to-assessment-question", "displayId": "feature/ULTRA-11163-patch-goal-alignments-to-assessment-question", "latestChangeset": "07d4a9749a09d4891b82fcb55bc1883f6b2a17b9", "latestCommit": "07d4a9749a09d4PI:PASSWORD:<PASSWORD>END_PI2fcbPI:PASSWORD:<PASSWORD>END_PI", "repository": { "slug": "b2-assessment", "id": 4856, "name": "b2-assessment", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "PI:KEY:<KEY>END_PI", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-assessment/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-assessment.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "64855a8fa223006c10ff8801e28534cee8395d19", "latestCommit": "64855a8fa223006c10ff8801e28534cee8395d19", "repository": { "slug": "b2-assessment", "id": 4856, "name": "b2-assessment", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "PI:KEY:<KEY>END_PI", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-assessment/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-assessment.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-assessment.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "PI:EMAIL:<EMAIL>END_PI", "id": 6255, "displayName": "PI:NAME:<NAME>END_PI", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/b2-assessment/pull-requests/88", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-assessment/pull-requests/88" }] } }, { "id": 8, "version": 0, "title": "ULTRA-11163-patch-goal-alignments", "description": "Renaming the parameter", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456108362134, "updatedDate": 1456108362134, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments", "displayId": "feature/ULTRA-11163-patch-goal-alignments", "latestChangeset": "e61cfb1d6659d5738e144ec8fbe866ed7e82a827", "latestCommit": "PI:PASSWORD:<PASSWORD>END_PI44PI:PASSWORD:<PASSWORD>END_PI8PI:PASSWORD:<PASSWORD>END_PI866PI:PASSWORD:<PASSWORD>END_PI7e8PI:PASSWORD:<PASSWORD>END_PI", "repository": { "slug": "apis-goal-api", "id": 4815, "name": "apis-goal-api", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "PI:KEY:<KEY>END_PI", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/apis-goal-api/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "links": { "clone": [{ "href": "ssh://git@stash.bbpd.io/learn/apis-goal-api.git", "name": "ssh" }, { "href": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "name": "http" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "4d3b2c2130281a942b9532fe32d09b2ec3b76456", "latestCommit": "4d3b2c2130281a942b9532fe32d09b2ec3b76456", "repository": { "slug": "apis-goal-api", "id": 4815, "name": "apis-goal-api", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "PI:KEY:<KEY>END_PI", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/apis-goal-api/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "links": { "clone": [{ "href": "ssh://git@stash.bbpd.io/learn/apis-goal-api.git", "name": "ssh" }, { "href": "https://mfu@stash.bbpd.io/scm/learn/apis-goal-api.git", "name": "http" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "PI:EMAIL:<EMAIL>END_PI", "id": 6255, "displayName": "PI:NAME:<NAME>END_PI", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [{ "user": { "name": "jima", "emailAddress": "PI:EMAIL:<EMAIL>END_PI", "id": 6354, "displayName": "PI:NAME:<NAME>END_PI", "active": true, "slug": "jima", "type": "NORMAL", "link": { "url": "/users/jima", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/jima" }] }, "avatarUrl": "https://secure.gravatar.com/avatar/0bfb0100e67c62eda7eaf3763b760d05.jpg?s=64&d=mm" }, "role": "REVIEWER", "approved": false }], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/apis-goal-api/pull-requests/8", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/apis-goal-api/pull-requests/8" }] } }, { "id": 14, "version": 0, "title": "ULTRA-11163-patch-goal-alignments", "description": "Renaming the parameter", "state": "OPEN", "open": true, "closed": false, "createdDate": 1456108338039, "updatedDate": 1456108338039, "fromRef": { "id": "refs/heads/feature/ULTRA-11163-patch-goal-alignments", "displayId": "feature/ULTRA-11163-patch-goal-alignments", "latestChangeset": "d05ceefeed509d12101de4c43e97ed6d0c2d51a3", "latestCommit": "d05ceefeed509d12101de4c43e97ed6d0c2d51a3", "repository": { "slug": "b2-goal", "id": 4912, "name": "b2-goal", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "learn", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-goal/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-goal.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/browse" }] } } }, "toRef": { "id": "refs/heads/develop", "displayId": "develop", "latestChangeset": "210ff66855824b80413286b660314a78669b918b", "latestCommit": "210ff66855824b80413286b660314a78669b918b", "repository": { "slug": "b2-goal", "id": 4912, "name": "b2-goal", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "LEARN", "id": 185, "name": "PI:NAME:<NAME>END_PI", "description": "Projects related to the Learn product line and/or Learn product development", "public": false, "type": "NORMAL", "link": { "url": "/projects/LEARN", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN" }] }, "avatarUrl": "/projects/LEARN/avatar.png?s=64&v=1437381065158" }, "public": false, "link": { "url": "/projects/LEARN/repos/b2-goal/browse", "rel": "self" }, "cloneUrl": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "links": { "clone": [{ "href": "https://mfu@stash.bbpd.io/scm/learn/b2-goal.git", "name": "http" }, { "href": "ssh://git@stash.bbpd.io/learn/b2-goal.git", "name": "ssh" }], "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/browse" }] } } }, "locked": false, "author": { "user": { "name": "mfu", "emailAddress": "PI:EMAIL:<EMAIL>END_PI", "id": 6255, "displayName": "PI:NAME:<NAME>END_PI", "active": true, "slug": "mfu", "type": "NORMAL", "link": { "url": "/users/mfu", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/mfu" }] }, "avatarUrl": "/users/mfu/avatar.png?s=64&v=1447136497000" }, "role": "AUTHOR", "approved": false }, "reviewers": [{ "user": { "name": "jima", "emailAddress": "PI:EMAIL:<EMAIL>END_PI", "id": 6354, "displayName": "PI:NAME:<NAME>END_PI", "active": true, "slug": "jima", "type": "NORMAL", "link": { "url": "/users/jima", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/users/jima" }] }, "avatarUrl": "https://secure.gravatar.com/avatar/0bfb0100e67c62eda7eaf3763b760d05.jpg?s=64&d=mm" }, "role": "REVIEWER", "approved": false }], "participants": [], "attributes": { "resolvedTaskCount": ["0"], "openTaskCount": ["0"] }, "link": { "url": "/projects/LEARN/repos/b2-goal/pull-requests/14", "rel": "self" }, "links": { "self": [{ "href": "https://stash.bbpd.io/projects/LEARN/repos/b2-goal/pull-requests/14" }] } }], "start": 0
[ { "context": "_bar_', '.Foo09-_bar']\n BAD_DSIDS = ['', 'A', 'foo@bar.com', Array(66).join('x'), '.', 'foo.', '.foo.bar']\n\n", "end": 2157, "score": 0.9999224543571472, "start": 2146, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "', ':' + Array(64).join('x')]\n BAD_IDS = ['', 'foo@bar.com', Array(66).join('x'), ':', ':' + Array(65).join(", "end": 2337, "score": 0.9999213218688965, "start": 2326, "tag": "EMAIL", "value": "foo@bar.com" } ]
test/src/fast/datastore/datastore_test.coffee
noamraph/datastore-js
0
impl = Dropbox.Datastore.impl Delta = impl.Delta class FakeClient constructor: (snapshotReturn = { rev: 0, rows: [], role: impl.ROLE_OWNER }) -> @_snapshotReturn = snapshotReturn isAuthenticated: -> true _datastoreAwait: -> # TODO: do something _getOrCreateDatastore: (dsid, cb) -> cb null, { handle: "handle", created: true } _createDatastore: (dsid, key, cb) -> cb null, { handle: "handle", created: true } _getSnapshot: (handle, cb) -> cb null, @_snapshotReturn _putDelta: (handle, delta, cb) -> # Most of these tests happen to rely on the server not acknowledging incoming deltas. if @putDeltaReturn? cb null, @putDeltaReturn describe 'Dropbox.Datastore', -> beforeEach (next) -> @client = new FakeClient @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openDefaultDatastore (err, datastore) => @datastore = datastore throw err if err @table = @datastore.getTable 'table' next() # TODO: test what happens when remote deletes a record and # re-creates a record with the same id. should probably get two # record objects in the RecordsChanged notification? it 'disallows opening the same datastore multiple times', -> expect(=> @datastoreManager.openDefaultDatastore (err, datastore) => throw new Error "should not have been allowed" ).to.throw "Attempt to open datastore multiple times" it 'allows reopening after closing', (done) -> @datastore.close() # expect not to throw @datastoreManager.openDefaultDatastore (err, datastore) => done() it 'RecordsChanged has a decent toString', (done) -> @datastore.recordsChanged.addListener (e) -> expect("" + e).to.equal "Datastore.RecordsChanged(1 record in 1 table changed locally)" done() @table.insert {} # TODO: test that uploads still finish after closing a datastore describe 'isValidId', -> # Array(n+1).join(s) repeats s n times. GOOD_DSIDS = ['1', 'foo', Array(65).join('x'), 'foo.bar', 'foo...bar', '-foo-bar-', '_foo_bar_', '.Foo09-_bar'] BAD_DSIDS = ['', 'A', 'foo@bar.com', Array(66).join('x'), '.', 'foo.', '.foo.bar'] GOOD_IDS = ['1', 'foo', 'Foo-_+.=Bar', Array(65).join('x'), ':foo', ':' + Array(64).join('x')] BAD_IDS = ['', 'foo@bar.com', Array(66).join('x'), ':', ':' + Array(65).join('x')] it 'accepts good datastore names', -> for id in GOOD_DSIDS expect(Dropbox.Datastore.isValidId(id)).to.equal true expect(Dropbox.Datastore.isValidShareableId(id)).to.equal (id.slice(0, 1) == '.') it 'rejects bad datastore names', -> for id in BAD_DSIDS expect(Dropbox.Datastore.isValidId(id)).to.equal false expect(Dropbox.Datastore.isValidShareableId(id)).to.equal false it 'accepts good table names', -> for id in GOOD_IDS expect(Dropbox.Datastore.Table.isValidId(id)).to.equal true it 'rejects bad table names', -> for id in BAD_IDS expect(Dropbox.Datastore.Table.isValidId(id)).to.equal false it 'accepts good record names', -> for id in GOOD_IDS expect(Dropbox.Datastore.Record.isValidId(id)).to.equal true it 'rejects bad record names', -> for id in BAD_IDS expect(Dropbox.Datastore.Record.isValidId(id)).to.equal false describe 'getTitle', -> it 'correctly gets the title', -> @datastore.setTitle 'title' expect(@datastore.getTitle()).to.equal 'title' it 'returns null if wasn\'t set', -> expect(@datastore.getTitle()).to.equal null it 'handles deletions of the info record', -> @datastore.setTitle 'title' record = @datastore.getTable(':info').get("info") record.deleteRecord() expect(@datastore.getTitle()).to.equal null it 'gets title correctly from the server', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', ':info', 'info', { title: 'serverTitle' }] ] } @datastore._sync() expect(@datastore.getTitle()).to.equal 'serverTitle' describe 'sharing behaviors for private datastores', -> it 'returns dummy values from basic sharing inquiries', -> expect(@datastore.isShareable()).to.equal false expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.OWNER expect(@datastore.isWritable()).to.equal true it 'throws on all advanced sharing calls', -> expect(=> @datastore.getRole Dropbox.Datastore.PUBLIC).to.throw() expect(=> @datastore.setRole Dropbox.Datastore.PUBLIC, Dropbox.Datastore.EDITOR).to.throw() expect(=> @datastore.deleteRole Dropbox.Datastore.PUBLIC).to.throw() expect(=> @datastore.listRole()).to.throw() describe 'getSize', -> beforeEach -> @empty_size = @datastore.getSize() it 'gets the empty datastore size correctly', -> # An empty datastore will have an ":info" table with an "mtime" field. size = (Dropbox.Datastore.BASE_DATASTORE_SIZE + Dropbox.Datastore.Record.BASE_RECORD_SIZE + Dropbox.Datastore.Record.BASE_FIELD_SIZE) expect(@empty_size).to.equal size it 'calculates the size of local changes', -> record = @table.insert { "foo": [1, 2, 3], "bar": 42 } record_size = (Dropbox.Datastore.Record.BASE_RECORD_SIZE + 2 * Dropbox.Datastore.Record.BASE_FIELD_SIZE + 3 * Dropbox.Datastore.List.BASE_ITEM_SIZE) expect(record.getSize()).to.equal record_size expect(@datastore.getSize()).to.equal @empty_size + record_size record.update { "bar": 0 } expect(record.getSize()).to.equal record_size record.update { "bar": 0 } expect(record.getSize()).to.equal record_size record.deleteRecord() expect(@datastore.getSize()).to.equal @empty_size it 'calculates the size of remote changes', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', 'table', 'record', { foo: 42 }] ] } @datastore._sync() size = (@empty_size + Dropbox.Datastore.Record.BASE_RECORD_SIZE + Dropbox.Datastore.Record.BASE_FIELD_SIZE) expect(@datastore.getSize()).to.equal size sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['D', 'table', 'record'] ] } @datastore._sync() expect(@datastore.getSize()).to.equal @empty_size describe 'getRecordCount', -> it 'gets the record count correctly', -> # "mtime" in the ":info" table. expect(@datastore.getRecordCount()).to.equal 1 describe 'with one record insertion', -> beforeEach -> # HACK(dropbox): forced it to not update the mtime @datastore._managed_datastore._update_mtime_on_change = false @record = @table.insert {} # TODO(dropbox): this should produce changes once the server allows that. it 'allows redundant deletions without producing outgoing changes', -> # 1 unsynced change: insert the record expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 1 expect(@record.get 'foo').to.equal null @record.set 'foo', null # nothing should happen after setting foo to null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 1 expect(@record.get 'foo').to.equal null @record.set 'foo', 1 # length should increase expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 2 expect(@record.get 'foo').to.equal 1 @record.set 'foo', null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 3 expect(@record.get 'foo').to.equal null @record.set 'foo', null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 3 expect(@record.get 'foo').to.equal null it 'handles redundant incoming field deletions', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state expect(managed_datastore.get_incoming_delta_count()).to.equal 0 sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', 'table', 'record', { foo: 'bar' }] ] } expect(managed_datastore.get_incoming_delta_count()).to.equal 1 expect(@table.get 'record').to.equal null @datastore._sync() expect(managed_datastore.get_incoming_delta_count()).to.equal 0 expect((@table.get 'record').getFields()).to.deep.equal { foo: 'bar' } sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ] } @datastore._sync() expect((@table.get 'record').getFields()).to.deep.equal {} sync_state.receive_server_delta new Delta { rev: 2, nonce: 'not_ours', changes: [ ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ] } @datastore._sync() expect((@table.get 'record').getFields()).to.deep.equal {} it 'allows colons in table and record ids in incoming changes', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', ':table', ':record', { ':foo': 'bar', ':bar': 'foo' }] ] } expect(@datastore.getTable(':table').get(':record')).to.equal null @datastore._sync() expect(@datastore.getTable(':table').get(':record').getFields()).to.deep.equal { ':foo': 'bar', ':bar': 'foo' } sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['U', ':table', ':record', { ':foo': ['P', 'baz'], ':baz': ['P', 'foo'], ':bar': ['D'] }] ] } @datastore._sync() expect(@datastore.getTable(':table').get(':record').getFields()).to.deep.equal { ':foo': 'baz', ':baz': 'foo' } describe 'Dropbox.Datastore for shareable datastores', -> beforeEach (next) -> @client = new FakeClient @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err next() it 'supports basic sharing inquiries', -> expect(@datastore.isShareable()).to.equal true expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.OWNER expect(@datastore.isWritable()).to.equal true it 'supports advanced sharing inquiries', -> expect(@datastore.getRole Dropbox.Datastore.TEAM).to.equal Dropbox.Datastore.NONE expect(@datastore.getRole Dropbox.Datastore.PUBLIC).to.equal Dropbox.Datastore.NONE expect(@datastore.listRoles()).to.deep.equal({}) it 'supports ACL changes', -> @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.EDITOR @datastore.setRole Dropbox.Datastore.PUBLIC, Dropbox.Datastore.VIEWER @datastore._sync() expect(@datastore.getRole Dropbox.Datastore.TEAM).to.equal Dropbox.Datastore.EDITOR expect(@datastore.getRole Dropbox.Datastore.PUBLIC).to.equal Dropbox.Datastore.VIEWER expected = {} expected[Dropbox.Datastore.TEAM] = Dropbox.Datastore.EDITOR expected[Dropbox.Datastore.PUBLIC] = Dropbox.Datastore.VIEWER expect(@datastore.listRoles()).to.deep.equal expected @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.NONE @datastore.deleteRole Dropbox.Datastore.PUBLIC expect(@datastore.listRoles()).to.deep.equal {} describe 'Dropbox.Datastore support for other effective roles', -> it 'works for editor', -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.EDITOR # Cursory check that we can still make changes @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.VIEWER @datastore._sync() t = @datastore.getTable 'table' t.insert {} # :acl should not be listed as a table ID expect(@datastore.listTableIds()).to.deep.equal ['table'] it 'works for viewer', -> @client = new FakeClient { rev: 1, rows: [ { tid: "t1", rowid: "r1", data: {} } ], role: impl.ROLE_VIEWER } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.VIEWER # Check that we can still read stuff expect(@datastore.getTitle()).to.equal(null) expect(@datastore.getModifiedTime()).not.to.equal(null) expect(@datastore.getRole(Dropbox.Datastore.TEAM)).to.equal(Dropbox.Datastore.NONE) expect(@datastore.getRole(Dropbox.Datastore.PUBLIC)).to.equal(Dropbox.Datastore.NONE) # Check that we can't make any changes expect(=> @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.VIEWER).to.throw() expect(=> @datastore.deleteRole Dropbox.Datastore.TEAM).to.throw() expect(=> @datastore.setTitle 'xyzzy').to.throw() t1 = @datastore.getTable 't1' expect(=> t1.insert {}).to.throw() expect(=> t1.getOrInsert 'r2', {}).to.throw() r1 = t1.get('r1') expect(=> r1.update { f1: 42 }).to.throw() expect(=> r1.set 'f1', 42).to.throw() expect(=> r1.deleteRecord()).to.throw() describe 'Dropbox.Datastore handling of access_denied errors', -> it 'works on the initial mtime change at creation', (done) -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @client.putDeltaReturn = { access_denied: "Test1" } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openOrCreateDatastore '.dsid', (err, datastore) => expect(datastore.getEffectiveRole()).to.equal Dropbox.Datastore.VIEWER expect(datastore.getSyncStatus()['uploading']).to.equal false done() it 'works on a later change', (done) -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @client.putDeltaReturn = { rev: 1 } # For the initial mtime update @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openOrCreateDatastore '.dsid', (err, datastore) => expect(datastore.getEffectiveRole()).to.equal Dropbox.Datastore.EDITOR expect(datastore.getSyncStatus()['uploading']).to.equal false @client.putDeltaReturn = { access_denied: "Test2" } datastore.recordsChanged.addListener (e) -> for r in e.affectedRecordsForTable('t1') if r.isDeleted() done() break datastore.getTable('t1').getOrInsert('r1', { f1: 42 })
628
impl = Dropbox.Datastore.impl Delta = impl.Delta class FakeClient constructor: (snapshotReturn = { rev: 0, rows: [], role: impl.ROLE_OWNER }) -> @_snapshotReturn = snapshotReturn isAuthenticated: -> true _datastoreAwait: -> # TODO: do something _getOrCreateDatastore: (dsid, cb) -> cb null, { handle: "handle", created: true } _createDatastore: (dsid, key, cb) -> cb null, { handle: "handle", created: true } _getSnapshot: (handle, cb) -> cb null, @_snapshotReturn _putDelta: (handle, delta, cb) -> # Most of these tests happen to rely on the server not acknowledging incoming deltas. if @putDeltaReturn? cb null, @putDeltaReturn describe 'Dropbox.Datastore', -> beforeEach (next) -> @client = new FakeClient @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openDefaultDatastore (err, datastore) => @datastore = datastore throw err if err @table = @datastore.getTable 'table' next() # TODO: test what happens when remote deletes a record and # re-creates a record with the same id. should probably get two # record objects in the RecordsChanged notification? it 'disallows opening the same datastore multiple times', -> expect(=> @datastoreManager.openDefaultDatastore (err, datastore) => throw new Error "should not have been allowed" ).to.throw "Attempt to open datastore multiple times" it 'allows reopening after closing', (done) -> @datastore.close() # expect not to throw @datastoreManager.openDefaultDatastore (err, datastore) => done() it 'RecordsChanged has a decent toString', (done) -> @datastore.recordsChanged.addListener (e) -> expect("" + e).to.equal "Datastore.RecordsChanged(1 record in 1 table changed locally)" done() @table.insert {} # TODO: test that uploads still finish after closing a datastore describe 'isValidId', -> # Array(n+1).join(s) repeats s n times. GOOD_DSIDS = ['1', 'foo', Array(65).join('x'), 'foo.bar', 'foo...bar', '-foo-bar-', '_foo_bar_', '.Foo09-_bar'] BAD_DSIDS = ['', 'A', '<EMAIL>', Array(66).join('x'), '.', 'foo.', '.foo.bar'] GOOD_IDS = ['1', 'foo', 'Foo-_+.=Bar', Array(65).join('x'), ':foo', ':' + Array(64).join('x')] BAD_IDS = ['', '<EMAIL>', Array(66).join('x'), ':', ':' + Array(65).join('x')] it 'accepts good datastore names', -> for id in GOOD_DSIDS expect(Dropbox.Datastore.isValidId(id)).to.equal true expect(Dropbox.Datastore.isValidShareableId(id)).to.equal (id.slice(0, 1) == '.') it 'rejects bad datastore names', -> for id in BAD_DSIDS expect(Dropbox.Datastore.isValidId(id)).to.equal false expect(Dropbox.Datastore.isValidShareableId(id)).to.equal false it 'accepts good table names', -> for id in GOOD_IDS expect(Dropbox.Datastore.Table.isValidId(id)).to.equal true it 'rejects bad table names', -> for id in BAD_IDS expect(Dropbox.Datastore.Table.isValidId(id)).to.equal false it 'accepts good record names', -> for id in GOOD_IDS expect(Dropbox.Datastore.Record.isValidId(id)).to.equal true it 'rejects bad record names', -> for id in BAD_IDS expect(Dropbox.Datastore.Record.isValidId(id)).to.equal false describe 'getTitle', -> it 'correctly gets the title', -> @datastore.setTitle 'title' expect(@datastore.getTitle()).to.equal 'title' it 'returns null if wasn\'t set', -> expect(@datastore.getTitle()).to.equal null it 'handles deletions of the info record', -> @datastore.setTitle 'title' record = @datastore.getTable(':info').get("info") record.deleteRecord() expect(@datastore.getTitle()).to.equal null it 'gets title correctly from the server', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', ':info', 'info', { title: 'serverTitle' }] ] } @datastore._sync() expect(@datastore.getTitle()).to.equal 'serverTitle' describe 'sharing behaviors for private datastores', -> it 'returns dummy values from basic sharing inquiries', -> expect(@datastore.isShareable()).to.equal false expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.OWNER expect(@datastore.isWritable()).to.equal true it 'throws on all advanced sharing calls', -> expect(=> @datastore.getRole Dropbox.Datastore.PUBLIC).to.throw() expect(=> @datastore.setRole Dropbox.Datastore.PUBLIC, Dropbox.Datastore.EDITOR).to.throw() expect(=> @datastore.deleteRole Dropbox.Datastore.PUBLIC).to.throw() expect(=> @datastore.listRole()).to.throw() describe 'getSize', -> beforeEach -> @empty_size = @datastore.getSize() it 'gets the empty datastore size correctly', -> # An empty datastore will have an ":info" table with an "mtime" field. size = (Dropbox.Datastore.BASE_DATASTORE_SIZE + Dropbox.Datastore.Record.BASE_RECORD_SIZE + Dropbox.Datastore.Record.BASE_FIELD_SIZE) expect(@empty_size).to.equal size it 'calculates the size of local changes', -> record = @table.insert { "foo": [1, 2, 3], "bar": 42 } record_size = (Dropbox.Datastore.Record.BASE_RECORD_SIZE + 2 * Dropbox.Datastore.Record.BASE_FIELD_SIZE + 3 * Dropbox.Datastore.List.BASE_ITEM_SIZE) expect(record.getSize()).to.equal record_size expect(@datastore.getSize()).to.equal @empty_size + record_size record.update { "bar": 0 } expect(record.getSize()).to.equal record_size record.update { "bar": 0 } expect(record.getSize()).to.equal record_size record.deleteRecord() expect(@datastore.getSize()).to.equal @empty_size it 'calculates the size of remote changes', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', 'table', 'record', { foo: 42 }] ] } @datastore._sync() size = (@empty_size + Dropbox.Datastore.Record.BASE_RECORD_SIZE + Dropbox.Datastore.Record.BASE_FIELD_SIZE) expect(@datastore.getSize()).to.equal size sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['D', 'table', 'record'] ] } @datastore._sync() expect(@datastore.getSize()).to.equal @empty_size describe 'getRecordCount', -> it 'gets the record count correctly', -> # "mtime" in the ":info" table. expect(@datastore.getRecordCount()).to.equal 1 describe 'with one record insertion', -> beforeEach -> # HACK(dropbox): forced it to not update the mtime @datastore._managed_datastore._update_mtime_on_change = false @record = @table.insert {} # TODO(dropbox): this should produce changes once the server allows that. it 'allows redundant deletions without producing outgoing changes', -> # 1 unsynced change: insert the record expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 1 expect(@record.get 'foo').to.equal null @record.set 'foo', null # nothing should happen after setting foo to null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 1 expect(@record.get 'foo').to.equal null @record.set 'foo', 1 # length should increase expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 2 expect(@record.get 'foo').to.equal 1 @record.set 'foo', null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 3 expect(@record.get 'foo').to.equal null @record.set 'foo', null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 3 expect(@record.get 'foo').to.equal null it 'handles redundant incoming field deletions', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state expect(managed_datastore.get_incoming_delta_count()).to.equal 0 sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', 'table', 'record', { foo: 'bar' }] ] } expect(managed_datastore.get_incoming_delta_count()).to.equal 1 expect(@table.get 'record').to.equal null @datastore._sync() expect(managed_datastore.get_incoming_delta_count()).to.equal 0 expect((@table.get 'record').getFields()).to.deep.equal { foo: 'bar' } sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ] } @datastore._sync() expect((@table.get 'record').getFields()).to.deep.equal {} sync_state.receive_server_delta new Delta { rev: 2, nonce: 'not_ours', changes: [ ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ] } @datastore._sync() expect((@table.get 'record').getFields()).to.deep.equal {} it 'allows colons in table and record ids in incoming changes', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', ':table', ':record', { ':foo': 'bar', ':bar': 'foo' }] ] } expect(@datastore.getTable(':table').get(':record')).to.equal null @datastore._sync() expect(@datastore.getTable(':table').get(':record').getFields()).to.deep.equal { ':foo': 'bar', ':bar': 'foo' } sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['U', ':table', ':record', { ':foo': ['P', 'baz'], ':baz': ['P', 'foo'], ':bar': ['D'] }] ] } @datastore._sync() expect(@datastore.getTable(':table').get(':record').getFields()).to.deep.equal { ':foo': 'baz', ':baz': 'foo' } describe 'Dropbox.Datastore for shareable datastores', -> beforeEach (next) -> @client = new FakeClient @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err next() it 'supports basic sharing inquiries', -> expect(@datastore.isShareable()).to.equal true expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.OWNER expect(@datastore.isWritable()).to.equal true it 'supports advanced sharing inquiries', -> expect(@datastore.getRole Dropbox.Datastore.TEAM).to.equal Dropbox.Datastore.NONE expect(@datastore.getRole Dropbox.Datastore.PUBLIC).to.equal Dropbox.Datastore.NONE expect(@datastore.listRoles()).to.deep.equal({}) it 'supports ACL changes', -> @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.EDITOR @datastore.setRole Dropbox.Datastore.PUBLIC, Dropbox.Datastore.VIEWER @datastore._sync() expect(@datastore.getRole Dropbox.Datastore.TEAM).to.equal Dropbox.Datastore.EDITOR expect(@datastore.getRole Dropbox.Datastore.PUBLIC).to.equal Dropbox.Datastore.VIEWER expected = {} expected[Dropbox.Datastore.TEAM] = Dropbox.Datastore.EDITOR expected[Dropbox.Datastore.PUBLIC] = Dropbox.Datastore.VIEWER expect(@datastore.listRoles()).to.deep.equal expected @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.NONE @datastore.deleteRole Dropbox.Datastore.PUBLIC expect(@datastore.listRoles()).to.deep.equal {} describe 'Dropbox.Datastore support for other effective roles', -> it 'works for editor', -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.EDITOR # Cursory check that we can still make changes @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.VIEWER @datastore._sync() t = @datastore.getTable 'table' t.insert {} # :acl should not be listed as a table ID expect(@datastore.listTableIds()).to.deep.equal ['table'] it 'works for viewer', -> @client = new FakeClient { rev: 1, rows: [ { tid: "t1", rowid: "r1", data: {} } ], role: impl.ROLE_VIEWER } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.VIEWER # Check that we can still read stuff expect(@datastore.getTitle()).to.equal(null) expect(@datastore.getModifiedTime()).not.to.equal(null) expect(@datastore.getRole(Dropbox.Datastore.TEAM)).to.equal(Dropbox.Datastore.NONE) expect(@datastore.getRole(Dropbox.Datastore.PUBLIC)).to.equal(Dropbox.Datastore.NONE) # Check that we can't make any changes expect(=> @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.VIEWER).to.throw() expect(=> @datastore.deleteRole Dropbox.Datastore.TEAM).to.throw() expect(=> @datastore.setTitle 'xyzzy').to.throw() t1 = @datastore.getTable 't1' expect(=> t1.insert {}).to.throw() expect(=> t1.getOrInsert 'r2', {}).to.throw() r1 = t1.get('r1') expect(=> r1.update { f1: 42 }).to.throw() expect(=> r1.set 'f1', 42).to.throw() expect(=> r1.deleteRecord()).to.throw() describe 'Dropbox.Datastore handling of access_denied errors', -> it 'works on the initial mtime change at creation', (done) -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @client.putDeltaReturn = { access_denied: "Test1" } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openOrCreateDatastore '.dsid', (err, datastore) => expect(datastore.getEffectiveRole()).to.equal Dropbox.Datastore.VIEWER expect(datastore.getSyncStatus()['uploading']).to.equal false done() it 'works on a later change', (done) -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @client.putDeltaReturn = { rev: 1 } # For the initial mtime update @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openOrCreateDatastore '.dsid', (err, datastore) => expect(datastore.getEffectiveRole()).to.equal Dropbox.Datastore.EDITOR expect(datastore.getSyncStatus()['uploading']).to.equal false @client.putDeltaReturn = { access_denied: "Test2" } datastore.recordsChanged.addListener (e) -> for r in e.affectedRecordsForTable('t1') if r.isDeleted() done() break datastore.getTable('t1').getOrInsert('r1', { f1: 42 })
true
impl = Dropbox.Datastore.impl Delta = impl.Delta class FakeClient constructor: (snapshotReturn = { rev: 0, rows: [], role: impl.ROLE_OWNER }) -> @_snapshotReturn = snapshotReturn isAuthenticated: -> true _datastoreAwait: -> # TODO: do something _getOrCreateDatastore: (dsid, cb) -> cb null, { handle: "handle", created: true } _createDatastore: (dsid, key, cb) -> cb null, { handle: "handle", created: true } _getSnapshot: (handle, cb) -> cb null, @_snapshotReturn _putDelta: (handle, delta, cb) -> # Most of these tests happen to rely on the server not acknowledging incoming deltas. if @putDeltaReturn? cb null, @putDeltaReturn describe 'Dropbox.Datastore', -> beforeEach (next) -> @client = new FakeClient @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openDefaultDatastore (err, datastore) => @datastore = datastore throw err if err @table = @datastore.getTable 'table' next() # TODO: test what happens when remote deletes a record and # re-creates a record with the same id. should probably get two # record objects in the RecordsChanged notification? it 'disallows opening the same datastore multiple times', -> expect(=> @datastoreManager.openDefaultDatastore (err, datastore) => throw new Error "should not have been allowed" ).to.throw "Attempt to open datastore multiple times" it 'allows reopening after closing', (done) -> @datastore.close() # expect not to throw @datastoreManager.openDefaultDatastore (err, datastore) => done() it 'RecordsChanged has a decent toString', (done) -> @datastore.recordsChanged.addListener (e) -> expect("" + e).to.equal "Datastore.RecordsChanged(1 record in 1 table changed locally)" done() @table.insert {} # TODO: test that uploads still finish after closing a datastore describe 'isValidId', -> # Array(n+1).join(s) repeats s n times. GOOD_DSIDS = ['1', 'foo', Array(65).join('x'), 'foo.bar', 'foo...bar', '-foo-bar-', '_foo_bar_', '.Foo09-_bar'] BAD_DSIDS = ['', 'A', 'PI:EMAIL:<EMAIL>END_PI', Array(66).join('x'), '.', 'foo.', '.foo.bar'] GOOD_IDS = ['1', 'foo', 'Foo-_+.=Bar', Array(65).join('x'), ':foo', ':' + Array(64).join('x')] BAD_IDS = ['', 'PI:EMAIL:<EMAIL>END_PI', Array(66).join('x'), ':', ':' + Array(65).join('x')] it 'accepts good datastore names', -> for id in GOOD_DSIDS expect(Dropbox.Datastore.isValidId(id)).to.equal true expect(Dropbox.Datastore.isValidShareableId(id)).to.equal (id.slice(0, 1) == '.') it 'rejects bad datastore names', -> for id in BAD_DSIDS expect(Dropbox.Datastore.isValidId(id)).to.equal false expect(Dropbox.Datastore.isValidShareableId(id)).to.equal false it 'accepts good table names', -> for id in GOOD_IDS expect(Dropbox.Datastore.Table.isValidId(id)).to.equal true it 'rejects bad table names', -> for id in BAD_IDS expect(Dropbox.Datastore.Table.isValidId(id)).to.equal false it 'accepts good record names', -> for id in GOOD_IDS expect(Dropbox.Datastore.Record.isValidId(id)).to.equal true it 'rejects bad record names', -> for id in BAD_IDS expect(Dropbox.Datastore.Record.isValidId(id)).to.equal false describe 'getTitle', -> it 'correctly gets the title', -> @datastore.setTitle 'title' expect(@datastore.getTitle()).to.equal 'title' it 'returns null if wasn\'t set', -> expect(@datastore.getTitle()).to.equal null it 'handles deletions of the info record', -> @datastore.setTitle 'title' record = @datastore.getTable(':info').get("info") record.deleteRecord() expect(@datastore.getTitle()).to.equal null it 'gets title correctly from the server', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', ':info', 'info', { title: 'serverTitle' }] ] } @datastore._sync() expect(@datastore.getTitle()).to.equal 'serverTitle' describe 'sharing behaviors for private datastores', -> it 'returns dummy values from basic sharing inquiries', -> expect(@datastore.isShareable()).to.equal false expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.OWNER expect(@datastore.isWritable()).to.equal true it 'throws on all advanced sharing calls', -> expect(=> @datastore.getRole Dropbox.Datastore.PUBLIC).to.throw() expect(=> @datastore.setRole Dropbox.Datastore.PUBLIC, Dropbox.Datastore.EDITOR).to.throw() expect(=> @datastore.deleteRole Dropbox.Datastore.PUBLIC).to.throw() expect(=> @datastore.listRole()).to.throw() describe 'getSize', -> beforeEach -> @empty_size = @datastore.getSize() it 'gets the empty datastore size correctly', -> # An empty datastore will have an ":info" table with an "mtime" field. size = (Dropbox.Datastore.BASE_DATASTORE_SIZE + Dropbox.Datastore.Record.BASE_RECORD_SIZE + Dropbox.Datastore.Record.BASE_FIELD_SIZE) expect(@empty_size).to.equal size it 'calculates the size of local changes', -> record = @table.insert { "foo": [1, 2, 3], "bar": 42 } record_size = (Dropbox.Datastore.Record.BASE_RECORD_SIZE + 2 * Dropbox.Datastore.Record.BASE_FIELD_SIZE + 3 * Dropbox.Datastore.List.BASE_ITEM_SIZE) expect(record.getSize()).to.equal record_size expect(@datastore.getSize()).to.equal @empty_size + record_size record.update { "bar": 0 } expect(record.getSize()).to.equal record_size record.update { "bar": 0 } expect(record.getSize()).to.equal record_size record.deleteRecord() expect(@datastore.getSize()).to.equal @empty_size it 'calculates the size of remote changes', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', 'table', 'record', { foo: 42 }] ] } @datastore._sync() size = (@empty_size + Dropbox.Datastore.Record.BASE_RECORD_SIZE + Dropbox.Datastore.Record.BASE_FIELD_SIZE) expect(@datastore.getSize()).to.equal size sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['D', 'table', 'record'] ] } @datastore._sync() expect(@datastore.getSize()).to.equal @empty_size describe 'getRecordCount', -> it 'gets the record count correctly', -> # "mtime" in the ":info" table. expect(@datastore.getRecordCount()).to.equal 1 describe 'with one record insertion', -> beforeEach -> # HACK(dropbox): forced it to not update the mtime @datastore._managed_datastore._update_mtime_on_change = false @record = @table.insert {} # TODO(dropbox): this should produce changes once the server allows that. it 'allows redundant deletions without producing outgoing changes', -> # 1 unsynced change: insert the record expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 1 expect(@record.get 'foo').to.equal null @record.set 'foo', null # nothing should happen after setting foo to null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 1 expect(@record.get 'foo').to.equal null @record.set 'foo', 1 # length should increase expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 2 expect(@record.get 'foo').to.equal 1 @record.set 'foo', null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 3 expect(@record.get 'foo').to.equal null @record.set 'foo', null expect(@datastore._managed_datastore.sync_state.unsynced_deltas.length).to.equal 2 expect(@datastore._managed_datastore.sync_state.unsynced_deltas[1].changes.length).to.equal 3 expect(@record.get 'foo').to.equal null it 'handles redundant incoming field deletions', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state expect(managed_datastore.get_incoming_delta_count()).to.equal 0 sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', 'table', 'record', { foo: 'bar' }] ] } expect(managed_datastore.get_incoming_delta_count()).to.equal 1 expect(@table.get 'record').to.equal null @datastore._sync() expect(managed_datastore.get_incoming_delta_count()).to.equal 0 expect((@table.get 'record').getFields()).to.deep.equal { foo: 'bar' } sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ] } @datastore._sync() expect((@table.get 'record').getFields()).to.deep.equal {} sync_state.receive_server_delta new Delta { rev: 2, nonce: 'not_ours', changes: [ ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ['U', 'table', 'record', { foo: ['D'], bar: ['D'] }] ] } @datastore._sync() expect((@table.get 'record').getFields()).to.deep.equal {} it 'allows colons in table and record ids in incoming changes', -> managed_datastore = @datastore._managed_datastore sync_state = managed_datastore.sync_state sync_state.receive_server_delta new Delta { rev: 0, nonce: 'not_ours', changes: [ ['I', ':table', ':record', { ':foo': 'bar', ':bar': 'foo' }] ] } expect(@datastore.getTable(':table').get(':record')).to.equal null @datastore._sync() expect(@datastore.getTable(':table').get(':record').getFields()).to.deep.equal { ':foo': 'bar', ':bar': 'foo' } sync_state.receive_server_delta new Delta { rev: 1, nonce: 'not_ours', changes: [ ['U', ':table', ':record', { ':foo': ['P', 'baz'], ':baz': ['P', 'foo'], ':bar': ['D'] }] ] } @datastore._sync() expect(@datastore.getTable(':table').get(':record').getFields()).to.deep.equal { ':foo': 'baz', ':baz': 'foo' } describe 'Dropbox.Datastore for shareable datastores', -> beforeEach (next) -> @client = new FakeClient @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err next() it 'supports basic sharing inquiries', -> expect(@datastore.isShareable()).to.equal true expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.OWNER expect(@datastore.isWritable()).to.equal true it 'supports advanced sharing inquiries', -> expect(@datastore.getRole Dropbox.Datastore.TEAM).to.equal Dropbox.Datastore.NONE expect(@datastore.getRole Dropbox.Datastore.PUBLIC).to.equal Dropbox.Datastore.NONE expect(@datastore.listRoles()).to.deep.equal({}) it 'supports ACL changes', -> @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.EDITOR @datastore.setRole Dropbox.Datastore.PUBLIC, Dropbox.Datastore.VIEWER @datastore._sync() expect(@datastore.getRole Dropbox.Datastore.TEAM).to.equal Dropbox.Datastore.EDITOR expect(@datastore.getRole Dropbox.Datastore.PUBLIC).to.equal Dropbox.Datastore.VIEWER expected = {} expected[Dropbox.Datastore.TEAM] = Dropbox.Datastore.EDITOR expected[Dropbox.Datastore.PUBLIC] = Dropbox.Datastore.VIEWER expect(@datastore.listRoles()).to.deep.equal expected @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.NONE @datastore.deleteRole Dropbox.Datastore.PUBLIC expect(@datastore.listRoles()).to.deep.equal {} describe 'Dropbox.Datastore support for other effective roles', -> it 'works for editor', -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.EDITOR # Cursory check that we can still make changes @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.VIEWER @datastore._sync() t = @datastore.getTable 'table' t.insert {} # :acl should not be listed as a table ID expect(@datastore.listTableIds()).to.deep.equal ['table'] it 'works for viewer', -> @client = new FakeClient { rev: 1, rows: [ { tid: "t1", rowid: "r1", data: {} } ], role: impl.ROLE_VIEWER } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.createDatastore (err, datastore) => @datastore = datastore throw err if err expect(@datastore.getEffectiveRole()).to.equal Dropbox.Datastore.VIEWER # Check that we can still read stuff expect(@datastore.getTitle()).to.equal(null) expect(@datastore.getModifiedTime()).not.to.equal(null) expect(@datastore.getRole(Dropbox.Datastore.TEAM)).to.equal(Dropbox.Datastore.NONE) expect(@datastore.getRole(Dropbox.Datastore.PUBLIC)).to.equal(Dropbox.Datastore.NONE) # Check that we can't make any changes expect(=> @datastore.setRole Dropbox.Datastore.TEAM, Dropbox.Datastore.VIEWER).to.throw() expect(=> @datastore.deleteRole Dropbox.Datastore.TEAM).to.throw() expect(=> @datastore.setTitle 'xyzzy').to.throw() t1 = @datastore.getTable 't1' expect(=> t1.insert {}).to.throw() expect(=> t1.getOrInsert 'r2', {}).to.throw() r1 = t1.get('r1') expect(=> r1.update { f1: 42 }).to.throw() expect(=> r1.set 'f1', 42).to.throw() expect(=> r1.deleteRecord()).to.throw() describe 'Dropbox.Datastore handling of access_denied errors', -> it 'works on the initial mtime change at creation', (done) -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @client.putDeltaReturn = { access_denied: "Test1" } @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openOrCreateDatastore '.dsid', (err, datastore) => expect(datastore.getEffectiveRole()).to.equal Dropbox.Datastore.VIEWER expect(datastore.getSyncStatus()['uploading']).to.equal false done() it 'works on a later change', (done) -> @client = new FakeClient { rev: 0, rows: [], role: impl.ROLE_EDITOR } @client.putDeltaReturn = { rev: 1 } # For the initial mtime update @datastoreManager = new Dropbox.Datastore.DatastoreManager @client @datastoreManager.openOrCreateDatastore '.dsid', (err, datastore) => expect(datastore.getEffectiveRole()).to.equal Dropbox.Datastore.EDITOR expect(datastore.getSyncStatus()['uploading']).to.equal false @client.putDeltaReturn = { access_denied: "Test2" } datastore.recordsChanged.addListener (e) -> for r in e.affectedRecordsForTable('t1') if r.isDeleted() done() break datastore.getTable('t1').getOrInsert('r1', { f1: 42 })
[ { "context": "0.1\"')\n expect(path).toContain('\"author\": \"John Doe\"')\n expect(path).toContain('\"description\":", "end": 1271, "score": 0.999497652053833, "start": 1263, "tag": "NAME", "value": "John Doe" } ]
test/functionals/commands/generate/package.spec.coffee
bcmw/neat
1
require '../../../test_helper' Neat = require '../../../../lib/neat' {run} = require '../../../../lib/utils/commands' {print} = require 'util' options = {} # stderr: (data)-> print data # stdout: (data)-> print data describe 'when outside a project', -> beforeEach -> process.chdir TEST_TMP_DIR addFileMatchers this describe 'running `neat generate package.json`', -> it "should return a status of 1 and don't generate anything", -> ended = false runs -> args = [NEAT_BIN, 'generate', 'package.json'] run 'node', args, options, (status) -> expect(status).toBe(1) expect("#{TEST_TMP_DIR}/package.json").not.toExist() ended = true waitsFor progress(-> ended), 'Timed out', 10000 withProject 'neat_project', -> describe 'running `neat generate package.json`', -> args = [ NEAT_BIN, 'generate', 'package.json', ] it 'should generate a package.json file at the project root', (done) -> run 'node', args, (status) -> path = inProject "package.json" expect(path).toExist() expect(path).toContain('"name": "neat_project"') expect(path).toContain('"version": "0.0.1"') expect(path).toContain('"author": "John Doe"') expect(path).toContain('"description": "a description"') expect(path).toContain("\"neat\": \"#{Neat.meta.version}\"") kw = "\"keywords\": [\n \"foo\",\n \"bar\",\n \"baz\"\n ]" expect(path).toContain(kw) done()
168323
require '../../../test_helper' Neat = require '../../../../lib/neat' {run} = require '../../../../lib/utils/commands' {print} = require 'util' options = {} # stderr: (data)-> print data # stdout: (data)-> print data describe 'when outside a project', -> beforeEach -> process.chdir TEST_TMP_DIR addFileMatchers this describe 'running `neat generate package.json`', -> it "should return a status of 1 and don't generate anything", -> ended = false runs -> args = [NEAT_BIN, 'generate', 'package.json'] run 'node', args, options, (status) -> expect(status).toBe(1) expect("#{TEST_TMP_DIR}/package.json").not.toExist() ended = true waitsFor progress(-> ended), 'Timed out', 10000 withProject 'neat_project', -> describe 'running `neat generate package.json`', -> args = [ NEAT_BIN, 'generate', 'package.json', ] it 'should generate a package.json file at the project root', (done) -> run 'node', args, (status) -> path = inProject "package.json" expect(path).toExist() expect(path).toContain('"name": "neat_project"') expect(path).toContain('"version": "0.0.1"') expect(path).toContain('"author": "<NAME>"') expect(path).toContain('"description": "a description"') expect(path).toContain("\"neat\": \"#{Neat.meta.version}\"") kw = "\"keywords\": [\n \"foo\",\n \"bar\",\n \"baz\"\n ]" expect(path).toContain(kw) done()
true
require '../../../test_helper' Neat = require '../../../../lib/neat' {run} = require '../../../../lib/utils/commands' {print} = require 'util' options = {} # stderr: (data)-> print data # stdout: (data)-> print data describe 'when outside a project', -> beforeEach -> process.chdir TEST_TMP_DIR addFileMatchers this describe 'running `neat generate package.json`', -> it "should return a status of 1 and don't generate anything", -> ended = false runs -> args = [NEAT_BIN, 'generate', 'package.json'] run 'node', args, options, (status) -> expect(status).toBe(1) expect("#{TEST_TMP_DIR}/package.json").not.toExist() ended = true waitsFor progress(-> ended), 'Timed out', 10000 withProject 'neat_project', -> describe 'running `neat generate package.json`', -> args = [ NEAT_BIN, 'generate', 'package.json', ] it 'should generate a package.json file at the project root', (done) -> run 'node', args, (status) -> path = inProject "package.json" expect(path).toExist() expect(path).toContain('"name": "neat_project"') expect(path).toContain('"version": "0.0.1"') expect(path).toContain('"author": "PI:NAME:<NAME>END_PI"') expect(path).toContain('"description": "a description"') expect(path).toContain("\"neat\": \"#{Neat.meta.version}\"") kw = "\"keywords\": [\n \"foo\",\n \"bar\",\n \"baz\"\n ]" expect(path).toContain(kw) done()
[ { "context": "###\n# test/coverage/blanket.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Wrapper for bl", "end": 57, "score": 0.9997239112854004, "start": 46, "tag": "NAME", "value": "Dan Nichols" } ]
test/coverage/blanket.coffee
dlnichols/h_media
0
### # test/coverage/blanket.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Wrapper for blanket.js ### 'use strict' require('blanket')( #pattern: /\/h_media\/(test\/lib|lib)\// pattern: 'lib' loader: './node-loaders/coffee-script' 'data-cover-never': 'node_modules' 'data-cover-reporter-options': shortnames: true )
206419
### # test/coverage/blanket.coffee # # © 2014 <NAME> # See LICENSE for more details # # Wrapper for blanket.js ### 'use strict' require('blanket')( #pattern: /\/h_media\/(test\/lib|lib)\// pattern: 'lib' loader: './node-loaders/coffee-script' 'data-cover-never': 'node_modules' 'data-cover-reporter-options': shortnames: true )
true
### # test/coverage/blanket.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Wrapper for blanket.js ### 'use strict' require('blanket')( #pattern: /\/h_media\/(test\/lib|lib)\// pattern: 'lib' loader: './node-loaders/coffee-script' 'data-cover-never': 'node_modules' 'data-cover-reporter-options': shortnames: true )
[ { "context": "@_steps.slice()\n\n toJSON: ->\n me =\n name: @_name\n start: @_start\n me.details = @_detai", "end": 872, "score": 0.9686201810836792, "start": 870, "tag": "NAME", "value": "@_" }, { "context": "teps.slice()\n\n toJSON: ->\n me =\n name: @_name\n start: @_start\n me.details = @_details i", "end": 876, "score": 0.8438044786453247, "start": 872, "tag": "NAME", "value": "name" } ]
src/profiler.coffee
couchand/tinyprofiler
0
# base profiler # doesn't like to be explicitly constructed {EventEmitter2} = require 'eventemitter2' {diff, now} = require './time' class Profiler extends EventEmitter2 constructor: (parent_baseline, @_name, @_details) -> @_baseline = now() @_steps = [] @_start = diff parent_baseline or @_baseline end: -> @_length = diff @_baseline @emit 'end' isDone: -> @_length? step: (name, details, cb) -> if typeof name is 'function' cb = name name = details details = null else if typeof details is 'function' cb = details details = null step = new Profiler @_baseline, name, details @_steps.push step @emit 'step', step cb step if cb step stepSync: -> step = @step.apply this, arguments step.end() steps: -> @_steps.slice() toJSON: -> me = name: @_name start: @_start me.details = @_details if @_details me.length = @_length if @_length if @_steps.length me.steps = (step.toJSON() for step in @_steps) me module.exports = Profiler
38923
# base profiler # doesn't like to be explicitly constructed {EventEmitter2} = require 'eventemitter2' {diff, now} = require './time' class Profiler extends EventEmitter2 constructor: (parent_baseline, @_name, @_details) -> @_baseline = now() @_steps = [] @_start = diff parent_baseline or @_baseline end: -> @_length = diff @_baseline @emit 'end' isDone: -> @_length? step: (name, details, cb) -> if typeof name is 'function' cb = name name = details details = null else if typeof details is 'function' cb = details details = null step = new Profiler @_baseline, name, details @_steps.push step @emit 'step', step cb step if cb step stepSync: -> step = @step.apply this, arguments step.end() steps: -> @_steps.slice() toJSON: -> me = name: <NAME> <NAME> start: @_start me.details = @_details if @_details me.length = @_length if @_length if @_steps.length me.steps = (step.toJSON() for step in @_steps) me module.exports = Profiler
true
# base profiler # doesn't like to be explicitly constructed {EventEmitter2} = require 'eventemitter2' {diff, now} = require './time' class Profiler extends EventEmitter2 constructor: (parent_baseline, @_name, @_details) -> @_baseline = now() @_steps = [] @_start = diff parent_baseline or @_baseline end: -> @_length = diff @_baseline @emit 'end' isDone: -> @_length? step: (name, details, cb) -> if typeof name is 'function' cb = name name = details details = null else if typeof details is 'function' cb = details details = null step = new Profiler @_baseline, name, details @_steps.push step @emit 'step', step cb step if cb step stepSync: -> step = @step.apply this, arguments step.end() steps: -> @_steps.slice() toJSON: -> me = name: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI start: @_start me.details = @_details if @_details me.length = @_length if @_length if @_steps.length me.steps = (step.toJSON() for step in @_steps) me module.exports = Profiler
[ { "context": "gify\n \"mail_tel\": @mail\n \"password\": @password\n .then (result) =>\n @session ?= j._jar.st", "end": 4408, "score": 0.9985474348068237, "start": 4399, "tag": "PASSWORD", "value": "@password" } ]
lib/livenico.coffee
hdemon/livenico.js
1
net = require 'net' tough = require 'tough-cookie' request = require "request" Promise = require "bluebird" qs = require 'querystring' cheerio = require 'cheerio' _ = require 'lodash' require 'source-map-support' j = request.jar() request = request.defaults {jar: j} class Nico constructor: (args) -> @session = null {@mail, @password} = args getPlayerStatus: (id) -> new Request url: "http://live.nicovideo.jp/api/getplayerstatus?v=#{id}" .then (response) -> Promise.resolve response.body getFlv: (id) -> new Request url: "http://flapi.nicovideo.jp/api/getflv/#{id}" .then (response) -> Promise.resolve qs.parse response.body getWeyBackKey: (thread) -> new Request url: "http://watch.live.nicovideo.jp/api/getwaybackkey?thread=#{thread}" .then (response) -> Promise.resolve response.body.replace /waybackkey\=/, '' getMessage: (movieInfo) -> new Request method: "GET" url: "#{movieInfo.ms.replace 'api', 'api.json'}thread?res_from=-1000&version=20090904&thread=#{movieInfo.thread_id}" getLiveMovieCommentXmlBuffers: (playerStatusHash, options={when:''}) -> {addr, port, thread, user_id} = playerStatusHash new Promise (resolve, reject) => (@getWeyBackKey thread).then (weyBackKey) -> result = [] socket = new net.Socket({ writable: true, readable: true }) socket.connect port, addr socket.on "connect", -> socket.write "<thread thread=\"#{thread}\" version=\"20061206\" res_from=\"-1000\" when=\"#{options.when}\" waybackkey=\"#{weyBackKey}\" user_id=\"#{user_id}\" scores=\"1\" />\0" socket.end() socket.on "data", (data) -> result.push data socket.on "end", -> resolve result.join('').toString() getMovieCommentXml: (id) -> @login() .then => (@getFlv id) .then @getMessage getLiveMovieCommentXml: (id, options) -> @login() .then => (@getPlayerStatus id) .then(@parsePlayerStatus) .then (playerStatus) => return Promise.reject playerStatus.code if playerStatus.status == 'fail' return Promise.reject "'when' option must be later than live movie's open time." if playerStatus.open_time >= options.when @getLiveMovieCommentXmlBuffers playerStatus, options .catch Promise.reject getLiveMovieComments: (id, options) -> (@getLiveMovieCommentXml id, options).then @parseCommentXml getLiveMovieAllComments: (id) -> new Promise (resolve, reject) => array = [] recursion = (_when) => (@getLiveMovieCommentXml id, {when: _when}).then (xml) => array = (@parseCommentXml xml).concat array firstComment = _.first array if firstComment.no == '1' resolve array else recursion Number firstComment.date recursion parseInt Date.now() / 1000 parseCommentXml: (xml) -> $ = cheerio.load xml, {decodeEntities: false} _.map $('chat'), (el) -> _el = $(el) thread = _el.attr("thread") || null _no = _el.attr("no") || null vpos = _el.attr("vpos") || null date = _el.attr("date") || null date_usec = _el.attr("date_usec" || null) mail = _el.attr("mail") || null user_id = _el.attr("user_id") || null premium = _el.attr("premium") || null anonymity = _el.attr("anonymity") || null body = _el.text() || '' {thread, no:_no, vpos, date, date_usec, mail, user_id, premium, anonymity, body} parsePlayerStatus: (playerStatus) -> $ = cheerio.load playerStatus g = $('getplayerstatus') if g.find("error").html() addr = port = thread = user_id = null code = g.find('code').text() else addr = g.find('ms addr').text() port = g.find('ms port').text() thread = g.find('ms thread').text() user_id = g.find('user user_id').text() open_time = Number g.find('open_time').text() code = null status = g.attr('status') {addr, port, thread, user_id, open_time, status, code} login: -> return Promise.resolve() if @hasAvailableSession @session new Request url: "https://secure.nicovideo.jp/secure/login?site=niconico" jar: j method: "POST" headers: "Content-Type": "application/x-www-form-urlencoded" body: qs.stringify "mail_tel": @mail "password": @password .then (result) => @session ?= j._jar.store.idx['nicovideo.jp']['/'].user_session result hasAvailableSession: (session) -> @session && @session.toString().match /user_session\=user_session_\d*/ class Request constructor: (args) -> return new Promise (resolve, reject) -> request args, (error, response, body) -> if error reject error else resolve response module.exports = Nico
42749
net = require 'net' tough = require 'tough-cookie' request = require "request" Promise = require "bluebird" qs = require 'querystring' cheerio = require 'cheerio' _ = require 'lodash' require 'source-map-support' j = request.jar() request = request.defaults {jar: j} class Nico constructor: (args) -> @session = null {@mail, @password} = args getPlayerStatus: (id) -> new Request url: "http://live.nicovideo.jp/api/getplayerstatus?v=#{id}" .then (response) -> Promise.resolve response.body getFlv: (id) -> new Request url: "http://flapi.nicovideo.jp/api/getflv/#{id}" .then (response) -> Promise.resolve qs.parse response.body getWeyBackKey: (thread) -> new Request url: "http://watch.live.nicovideo.jp/api/getwaybackkey?thread=#{thread}" .then (response) -> Promise.resolve response.body.replace /waybackkey\=/, '' getMessage: (movieInfo) -> new Request method: "GET" url: "#{movieInfo.ms.replace 'api', 'api.json'}thread?res_from=-1000&version=20090904&thread=#{movieInfo.thread_id}" getLiveMovieCommentXmlBuffers: (playerStatusHash, options={when:''}) -> {addr, port, thread, user_id} = playerStatusHash new Promise (resolve, reject) => (@getWeyBackKey thread).then (weyBackKey) -> result = [] socket = new net.Socket({ writable: true, readable: true }) socket.connect port, addr socket.on "connect", -> socket.write "<thread thread=\"#{thread}\" version=\"20061206\" res_from=\"-1000\" when=\"#{options.when}\" waybackkey=\"#{weyBackKey}\" user_id=\"#{user_id}\" scores=\"1\" />\0" socket.end() socket.on "data", (data) -> result.push data socket.on "end", -> resolve result.join('').toString() getMovieCommentXml: (id) -> @login() .then => (@getFlv id) .then @getMessage getLiveMovieCommentXml: (id, options) -> @login() .then => (@getPlayerStatus id) .then(@parsePlayerStatus) .then (playerStatus) => return Promise.reject playerStatus.code if playerStatus.status == 'fail' return Promise.reject "'when' option must be later than live movie's open time." if playerStatus.open_time >= options.when @getLiveMovieCommentXmlBuffers playerStatus, options .catch Promise.reject getLiveMovieComments: (id, options) -> (@getLiveMovieCommentXml id, options).then @parseCommentXml getLiveMovieAllComments: (id) -> new Promise (resolve, reject) => array = [] recursion = (_when) => (@getLiveMovieCommentXml id, {when: _when}).then (xml) => array = (@parseCommentXml xml).concat array firstComment = _.first array if firstComment.no == '1' resolve array else recursion Number firstComment.date recursion parseInt Date.now() / 1000 parseCommentXml: (xml) -> $ = cheerio.load xml, {decodeEntities: false} _.map $('chat'), (el) -> _el = $(el) thread = _el.attr("thread") || null _no = _el.attr("no") || null vpos = _el.attr("vpos") || null date = _el.attr("date") || null date_usec = _el.attr("date_usec" || null) mail = _el.attr("mail") || null user_id = _el.attr("user_id") || null premium = _el.attr("premium") || null anonymity = _el.attr("anonymity") || null body = _el.text() || '' {thread, no:_no, vpos, date, date_usec, mail, user_id, premium, anonymity, body} parsePlayerStatus: (playerStatus) -> $ = cheerio.load playerStatus g = $('getplayerstatus') if g.find("error").html() addr = port = thread = user_id = null code = g.find('code').text() else addr = g.find('ms addr').text() port = g.find('ms port').text() thread = g.find('ms thread').text() user_id = g.find('user user_id').text() open_time = Number g.find('open_time').text() code = null status = g.attr('status') {addr, port, thread, user_id, open_time, status, code} login: -> return Promise.resolve() if @hasAvailableSession @session new Request url: "https://secure.nicovideo.jp/secure/login?site=niconico" jar: j method: "POST" headers: "Content-Type": "application/x-www-form-urlencoded" body: qs.stringify "mail_tel": @mail "password": <PASSWORD> .then (result) => @session ?= j._jar.store.idx['nicovideo.jp']['/'].user_session result hasAvailableSession: (session) -> @session && @session.toString().match /user_session\=user_session_\d*/ class Request constructor: (args) -> return new Promise (resolve, reject) -> request args, (error, response, body) -> if error reject error else resolve response module.exports = Nico
true
net = require 'net' tough = require 'tough-cookie' request = require "request" Promise = require "bluebird" qs = require 'querystring' cheerio = require 'cheerio' _ = require 'lodash' require 'source-map-support' j = request.jar() request = request.defaults {jar: j} class Nico constructor: (args) -> @session = null {@mail, @password} = args getPlayerStatus: (id) -> new Request url: "http://live.nicovideo.jp/api/getplayerstatus?v=#{id}" .then (response) -> Promise.resolve response.body getFlv: (id) -> new Request url: "http://flapi.nicovideo.jp/api/getflv/#{id}" .then (response) -> Promise.resolve qs.parse response.body getWeyBackKey: (thread) -> new Request url: "http://watch.live.nicovideo.jp/api/getwaybackkey?thread=#{thread}" .then (response) -> Promise.resolve response.body.replace /waybackkey\=/, '' getMessage: (movieInfo) -> new Request method: "GET" url: "#{movieInfo.ms.replace 'api', 'api.json'}thread?res_from=-1000&version=20090904&thread=#{movieInfo.thread_id}" getLiveMovieCommentXmlBuffers: (playerStatusHash, options={when:''}) -> {addr, port, thread, user_id} = playerStatusHash new Promise (resolve, reject) => (@getWeyBackKey thread).then (weyBackKey) -> result = [] socket = new net.Socket({ writable: true, readable: true }) socket.connect port, addr socket.on "connect", -> socket.write "<thread thread=\"#{thread}\" version=\"20061206\" res_from=\"-1000\" when=\"#{options.when}\" waybackkey=\"#{weyBackKey}\" user_id=\"#{user_id}\" scores=\"1\" />\0" socket.end() socket.on "data", (data) -> result.push data socket.on "end", -> resolve result.join('').toString() getMovieCommentXml: (id) -> @login() .then => (@getFlv id) .then @getMessage getLiveMovieCommentXml: (id, options) -> @login() .then => (@getPlayerStatus id) .then(@parsePlayerStatus) .then (playerStatus) => return Promise.reject playerStatus.code if playerStatus.status == 'fail' return Promise.reject "'when' option must be later than live movie's open time." if playerStatus.open_time >= options.when @getLiveMovieCommentXmlBuffers playerStatus, options .catch Promise.reject getLiveMovieComments: (id, options) -> (@getLiveMovieCommentXml id, options).then @parseCommentXml getLiveMovieAllComments: (id) -> new Promise (resolve, reject) => array = [] recursion = (_when) => (@getLiveMovieCommentXml id, {when: _when}).then (xml) => array = (@parseCommentXml xml).concat array firstComment = _.first array if firstComment.no == '1' resolve array else recursion Number firstComment.date recursion parseInt Date.now() / 1000 parseCommentXml: (xml) -> $ = cheerio.load xml, {decodeEntities: false} _.map $('chat'), (el) -> _el = $(el) thread = _el.attr("thread") || null _no = _el.attr("no") || null vpos = _el.attr("vpos") || null date = _el.attr("date") || null date_usec = _el.attr("date_usec" || null) mail = _el.attr("mail") || null user_id = _el.attr("user_id") || null premium = _el.attr("premium") || null anonymity = _el.attr("anonymity") || null body = _el.text() || '' {thread, no:_no, vpos, date, date_usec, mail, user_id, premium, anonymity, body} parsePlayerStatus: (playerStatus) -> $ = cheerio.load playerStatus g = $('getplayerstatus') if g.find("error").html() addr = port = thread = user_id = null code = g.find('code').text() else addr = g.find('ms addr').text() port = g.find('ms port').text() thread = g.find('ms thread').text() user_id = g.find('user user_id').text() open_time = Number g.find('open_time').text() code = null status = g.attr('status') {addr, port, thread, user_id, open_time, status, code} login: -> return Promise.resolve() if @hasAvailableSession @session new Request url: "https://secure.nicovideo.jp/secure/login?site=niconico" jar: j method: "POST" headers: "Content-Type": "application/x-www-form-urlencoded" body: qs.stringify "mail_tel": @mail "password": PI:PASSWORD:<PASSWORD>END_PI .then (result) => @session ?= j._jar.store.idx['nicovideo.jp']['/'].user_session result hasAvailableSession: (session) -> @session && @session.toString().match /user_session\=user_session_\d*/ class Request constructor: (args) -> return new Promise (resolve, reject) -> request args, (error, response, body) -> if error reject error else resolve response module.exports = Nico
[ { "context": "url\n\n# your google shortener API key?!\nAPI_KEY = 'AIzaSyAZ2wia3BqnEkJEBQ7WYiDw3_VMi0bCC8s'\n\n# app-defined mimetypes...\nmake_mimetypes = (fe", "end": 3543, "score": 0.9997344613075256, "start": 3504, "tag": "KEY", "value": "AIzaSyAZ2wia3BqnEkJEBQ7WYiDw3_VMi0bCC8s" } ]
cache_builder/cb.coffee
cgreenhalgh/opensharingtoolkit-kiosk
4
# coffee-script version of cache builder https = require 'https' http = require 'http' fs = require 'fs' xml2js = require 'xml2js' parse_url = (require 'url').parse resolve_url = (require 'url').resolve if process.argv.length<3 console.log 'usage: coffee cb.coffee <KIOSK-ATOM-FILE>' process.exit -1 # devices cofig devicesfn = "devices.json" console.log "read devices from #{devicesfn}" devicesin = fs.readFileSync devicesfn,'utf8' try devices = JSON.parse devicesin catch err console.log "Error parsing JSON from #{devicesfn}: #{err.message}" process.exit -1 # mimetypes defaults mimetypesinfn = "mimetypes-in.json" mimetypesfn = "mimetypes.json" console.log "read default mimetypes from #{mimetypesinfn}" mimetypesin = fs.readFileSync mimetypesinfn,'utf8' try mimetypes = JSON.parse mimetypesin catch err console.log "Error parsing JSON from #{mimetypesinfn}: #{err.message}" process.exit -1 # built-in mimetypes for mt,mtinfo of mimetypes console.log "Check default mimetype #{mt}" if not mtinfo.compat? mtinfo.compat = {} exclusive = false for dt,dtinfo of devices if dtinfo.supportsMimeExclusive? and dtinfo.supportsMimeExclusive.indexOf(mt) >= 0 exclusive = true for dt,dtinfo of devices #console.log "- against device #{dt}" dtcompat = {} if dtinfo.userAgentPattern? dtcompat.userAgentPattern = dtinfo.userAgentPattern if dtinfo.supportsMimeExclusive? and dtinfo.supportsMimeExclusive.indexOf(mt) >= 0 dtcompat.builtin = true else if dtinfo.supportsMime? and dtinfo.supportsMime.indexOf(mt) >= 0 dtcompat.builtin = true else if not dtinfo.optionalSupportsMime? or dtinfo.optionalSupportsMime.indexOf(mt) < 0 dtcompat.builtin = false # undefined = maybe / optional if exclusive dtcompat.appsComplete = true dtcompat.apps = [] mtinfo.compat[dt] = dtcompat console.log "Write initial mimetypes to #{mimetypesfn}" fs.writeFileSync mimetypesfn,JSON.stringify mimetypes # process atom file... atomfn = process.argv[2] parser = new xml2js.Parser() # is file hidden is_hidden = (entry) -> #console.dir entry for cs in entry.category ? [] when cs.$.scheme == 'visibility' and cs.$.term == 'hidden' return true return false # read main atom file console.log 'read '+atomfn data = fs.readFileSync atomfn, 'utf8' console.log 'read '+data.length+' bytes' # try reading shorturls.json shorturls = [] shorturlsfn = 'shorturls.json' try shorturlsdata = fs.readFileSync shorturlsfn,'utf8' shorturls = JSON.parse shorturlsdata catch e console.log 'could not read '+shorturlsfn+': '+e # try reading cache.json cache = {} cachefn = 'cache.json' try cachedata = fs.readFileSync cachefn,'utf8' cache = JSON.parse cachedata catch e console.log 'could not read '+cachefn+': '+e # make one shorturl add_shorturl = (shorturls,url) -> #console.log 'shorturl for '+url sus = for su in shorturls when su.url == url su.shorturl ? '' if sus.length == 0 # work out shorturl later shorturls.push { url: url } get_feedurl = (feed) -> feedurl = for link in feed.link when link.$.rel == 'self' link.$.href if feedurl.length < 1 console.log 'No self link found - cannot work out shorturls' process.exit -1 return feedurl[0] get_baseurl = (feed) -> baseurl = get_feedurl feed ix = baseurl.lastIndexOf '/' baseurl = baseurl.slice 0,ix+1 console.log 'Base URL = '+baseurl return baseurl # your google shortener API key?! API_KEY = 'AIzaSyAZ2wia3BqnEkJEBQ7WYiDw3_VMi0bCC8s' # app-defined mimetypes... make_mimetypes = (feed,mimetypes) -> console.log "make_mimetypes..." for appentry in feed.entry title = appentry.title[0] requires = for cat in appentry.category ? [] when cat.$.scheme == 'requires-device' and cat.$.term? cat.$.term supports = for cat in appentry.category ? [] when cat.$.scheme == 'supports-mime-type' and cat.$.term? { mime: cat.$.term, label: cat.$.label ?= cat.$.term } exclusive = for cat in appentry.category ? [] when cat.$.scheme == 'supports-mime-type-exclusive' and cat.$.term? cat.$.term appurls = for link in appentry.link ? [] when link.$.rel == 'enclosure' and link.$.href? link.$.href for device in requires for support in supports mt = support.mime if not mimetypes[mt]? mimetypes[mt] = { } mtinfo = mimetypes[mt] if support.label? and (not mtinfo.label? or mtinfo.label==mt) mtinfo.label = support.label # icon iconurls = for link in appentry.link ? [] when link.$.rel == 'alternate' and link.$.type? and link.$.href? and /^image/.test link.$.type link.$.href if iconurls.length > 0 and not mtinfo.icon? mtinfo.icon = iconurls[0] if not mtinfo.compat? mtinfo.compat = {} if not mtinfo.compat[device]? mtinfo.compat[device] = {} dtcompat = mtinfo.compat[device] if not dtcompat.userAgentPattern? and devices[device]?.userAgentPattern? dtcompat.userAgentPattern = devices[device].userAgentPattern if exclusive.length > 0 dtcompat.appsComplete = true if not dtcompat.apps? dtcompat.apps = [] for appurl in appurls dtcompat.apps.push { name: title, url: appurl } # shorturl for each make_shorturls = (feed,shorturls) -> console.log 'make_shorturls...' # campaignids... campaignids = for cat in feed.category ? [] when cat.$.scheme == 'campaign' and cat.$.term? cat.$.term campaignsuffix = for cid in campaignids '&c='+encodeURIComponent(cid) campaignsuffix.push '' # atom url -> get url baseurl = get_baseurl feed # .html?? .php for now! geturl = baseurl+'get.php' # request a short-url for internet kiosk view feedurl =get_feedurl feed kioskurl = baseurl+'index.html?f='+encodeURIComponent(feedurl) url = geturl+'?u='+encodeURIComponent(kioskurl)+'&t='+encodeURIComponent("Kiosk View") mimeparam = '&m='+encodeURIComponent('text/html') for cs in campaignsuffix add_shorturl shorturls,url+mimeparam+cs # qr flag add_shorturl shorturls,url+mimeparam+cs+'&qr' # device is now sniffed from agent only # work out URLs to be shortened # get.html?u=URL&t=TITLE[&m=MIMETYPE] # each entry... for entry in feed.entry when not is_hidden entry title = entry.title[0] # each enclosure for link in entry.link ?= [] when link.$.rel == 'enclosure' fileurl = link.$.href mime = link.$.type url = geturl+'?u='+encodeURIComponent(fileurl)+'&t='+encodeURIComponent(title) mimeparam = if mime? then '&m='+encodeURIComponent(mime) else '' for cs in campaignsuffix add_shorturl shorturls,url+mimeparam+cs # qr flag add_shorturl shorturls,url+mimeparam+cs+'&qr' # device is now sniffed from agent only add_fileurl = (url, fileurls) -> #console.log "check #{url}" # not sure why indexOf doesn't seem to match it us = for u in fileurls when u == url u if not us? or us.length == 0 #console.log 'add '+url+' to fileurls' fileurls.push url fix_relative_url = (url,path) -> resolve_url url, path # cache entry for each make_cache = (feed,cache) -> fileurls = [] for entry in feed.entry #console.dir entry hidden = is_hidden entry # atom enclosures for link in entry.link when link.$.href? and (link.$.rel == 'alternate' or not hidden) add_fileurl (fix_relative_url cache.baseurl, link.$.href), fileurls # media-rss media:thumbnail for thumbnail in (entry['media:thumbnail'] ? []) when thumbnail.$.url? add_fileurl (fix_relative_url cache.baseurl, thumbnail.$.url), fileurls console.dir fileurls oldfiles = cache.files ? [] cache.files = [] for file in oldfiles file.needed = false # does the file exist? if file.path? fileok = false try st = fs.statSync file.path if st.isFile() fileok = true else console.log 'old cache path not file: '+file.path catch e console.log 'old cache file not found: '+file.path if not fileok # doesn't exist, presumably delete file.path delete file.length delete file.lastmod for fileurl in fileurls file = { url: fileurl } oldfile = for f in oldfiles when f.url == fileurl f if oldfile.length > 0 file = oldfile[0] file.needed = true cache.files.push file #console.log "Add to cache #{file.url}" # un-needed files in cache? for oldfile in oldfiles when oldfile.path? and not oldfile.needed present = for f in cache.files when f.url == oldfile.url f if present.length==0 cache.files.push oldfile else console.log "Discard duplicate file cache entry #{oldfile.url}" get_filename_for_component = (h) -> if h=='' return '_' h = decodeURIComponent h return h.replace("~","_") # is that enough?? # get local cache path for an URL - like java cacheing, # maps domain name elements and path elements to folders get_cache_path = (url) -> url = parse_url url # hostname, port, path (includes query), hash hs = if url.hostname? then url.hostname.split '.' else [] # reverse non-IP order number = /^[0-9]+$/ ns = 0 for h in hs when number.test h ns++ if ns != hs.length hs.reverse # normalise domain name to lower case hs = for h in hs String(h).toLowerCase() # ignore port for now! ps = if url.path? then url.path.split '/' else [] # leading /? if ps.length>1 and ps[0]=='' ps.shift() hs = ["cache"].concat hs,ps # make safe filenames hs = for h in hs get_filename_for_component h path = hs.join '/' return path doneShorturls = false doneCache = false # may be present unneeded, or not add_cache_url = (cache,url,appcache) -> for f in cache.files when f.url == url if appcache? f.appcache = true if f.needed console.log "URL already needed: #{url}" return console.log "URL present, now needed: #{url}" f.needed = true return file = { url: url, needed: true } console.log "Add url #{url}" cache.files.push file check_appcache = (cache,file) -> if not file.path? return si = file.path.lastIndexOf '/' ei = file.path.lastIndexOf '.' extn = if ei<0 or ei<si then '' else file.path.substring(ei+1) if extn=='appcache' console.log "check appcache file #{file.url}" try appcache = fs.readFileSync file.path,{encoding:'utf8'} lines = appcache.split '\n' lines = for l in lines when l.trim().indexOf('#')!=0 and l.trim().length>0 l.trim() if lines.length<=0 console.log "Empty appcache manifest #{file.url}" return if lines[0]!='CACHE MANIFEST' console.log "Bad appcache manifest #{file.url}; first line #{lines[0]}" section = "CACHE:" for l,i in lines when i>0 if l=="CACHE:" or l=="SETTINGS:" or l=="NETWORK:" section = l else if section=="CACHE:" url = fix_relative_url file.url,l console.log "Found manifest entry #{l} -> #{url}" add_cache_url cache,url catch err console.log "Error checking appcache file #{file.path}: #{err}" check_html_file = (cache,ix,file) -> si = file.path.lastIndexOf '/' ei = file.path.lastIndexOf '.' extn = if ei<0 or ei<si then '' else file.path.substring(ei+1) if extn=='htm' or extn=='html' or extn=='xhtml' try html = fs.readFileSync file.path,{encoding:'utf8'} hi = html.indexOf '<html ' hi2 = html.indexOf '>',hi mi = html.indexOf ' manifest="', hi mi2 = html.indexOf '"', mi+11 if mi>=0 and mi2>=mi and mi2<hi2 manifest = (html.substring mi+11,mi2) # make absolute, schedule for download and check manifesturl = fix_relative_url file.url,manifest console.log "Found html manifest #{manifest} in #{file.url} -> #{manifesturl}" # set appcache flag add_cache_url cache,manifesturl,true catch err console.log "Error checking html file: #{err}" # parse file(s) and call worker(s) parser.parseString data,(err,result) -> if err console.log 'Error parsing '+atomfn+': '+err process.exit -1 feed = result.feed console.log 'Feed '+feed.title+' ('+feed.id+')' make_mimetypes feed,mimetypes console.log "write mimetypes to #{mimetypesfn}" fs.writeFileSync mimetypesfn,JSON.stringify mimetypes make_shorturls feed,shorturls fix_shorturls = (shorturls,i) -> if i >= shorturls.length # done console.log 'write shorturls.json' fs.writeFileSync shorturlsfn,JSON.stringify shorturls doneShorturls = true if doneShorturls and doneCache process.exit 0 else su = shorturls[i] if su.shorturl == undefined # see https://developers.google.com/url-shortener/v1/getting_started # POST application/json {"longUrl":"XXX"} -> # https://www.googleapis.com/urlshortener/v1/url # { "kind": "urlshortener#url", "id": "http://goo.gl/XXXX", # "longUrl": "XXX" } console.log 'Shorten '+su.url req = {longUrl: su.url} reqs = JSON.stringify req url = '/urlshortener/v1/url' if API_KEY? url = url+"?key="+API_KEY options = hostname: 'www.googleapis.com' path: url method: 'POST' headers: { 'content-type': 'application/json' } hreq = https.request options, (res) -> if res.statusCode != 200 console.log 'got shortener response '+res.statusCode process.exit -1 res.setEncoding 'utf8' data = '' res.on 'data',(chunk) -> #console.log 'shortener response: '+chunk data = data+chunk res.on 'end',()-> jres = JSON.parse data su.shorturl = jres.id console.log 'Shortened to '+su.shorturl # recurse fix_shorturls shorturls,i+1 hreq.on 'error',(e) -> console.log 'Error shortening url: '+e process.exit -1 hreq.end reqs #console.log 'sent '+reqs else # recurse fix_shorturls shorturls,i+1 fix_shorturls shorturls,0 # download icons and visible enclosures, populating cache.json baseurl = get_baseurl feed cache.baseurl = baseurl make_cache feed,cache fix_cache = (cache,ix) -> if ix >= cache.files.length # done! console.log 'write cache.json' fs.writeFileSync cachefn,JSON.stringify cache doneCache = true if doneShorturls and doneCache process.exit 0 else file = cache.files[ix] #console.log 'fix_cache '+ix+': '+file.url+', was '+file.path if file.needed and file.url.indexOf( cache.baseurl )==0 file.path = file.url.substring (cache.baseurl.length) console.log "local file #{file.url} -> #{file.path}" check_appcache cache,file check_html_file cache,ix,file fix_cache cache,ix+1 else if file.needed and file.path? check_file_modified cache,ix,file else if file.needed get_cache_file cache,ix,file else #check_appcache cache,file # not needed! fix_cache cache,ix+1 check_file_modified = (cache,ix,file) -> # if the local file exists and we have size and server last-modified, # try a head on the remote file with if-modified-since; # (prepare to) dump local copy if out of date # TODO if file.lastmod? console.log 'Check '+file.url url = parse_url file.url protocol = url.protocol ?= 'http' options = hostname: url.hostname port: url.port path: url.path auth: url.auth method: 'HEAD' headers: { 'if-modified-since': file.lastmod } pmodule = if protocol=='https' then https else http req = pmodule.request options,(res) -> res.on 'data',(data) -> ; # no op if res.statusCode == 304 console.log 'Not modified: '+file.url check_appcache cache,file fix_cache cache,ix+1 else console.log 'Check returned '+res.statusCode+'; assume modified' get_cache_file cache,ix,file req.on 'error',(e) -> console.log 'Error checking '+file.url+' ('+JSON.stringify( options )+'): '+e get_cache_file cache,ix,file req.end() else get_cache_file cache,ix,file get_cache_file = (cache,ix,file) -> # new local path = url mapped to folder hierarchy - domain name # in reverse order (ip forwards), port, path elements, # final filename+fragment+query path = file.path ? get_cache_path file.url #console.log 'new file path = '+path+' for '+file.url # check directory exists dir = '' ps = path.split '/' if ps.length>1 for i in [0..(ps.length-2)] dir = dir + (if i>0 then '/' else '') + ps[i] if !fs.existsSync(dir) fs.mkdirSync dir # if updated or missing attempt download, initially to temp file # and stash header last-modified and content-length url = parse_url file.url protocol = url.protocol ? 'http' options = method: 'GET' pmodule = if protocol=='https' then https else http console.log 'Download '+file.url req = pmodule.get file.url,(res) -> if res.statusCode != 200 console.log 'Error getting file '+file.url+', response '+res.statusCode fix_cache cache,ix+1 else # on success remove old file if present and link/rename new file lastmod = res.headers['last-modified'] length = res.headers['content-length'] tmppath = dir + (if dir!='' then '/' else '') + '.cb_download' try fd = fs.openSync(tmppath, 'w') catch e console.log 'Could not create tmpfile '+tmppath+': '+e return fix_cache cache,ix+1 count = 0; res.on 'data',(data) -> if count < 0 return #console.log 'got '+data.length+' bytes for '+file.url try fs.writeSync(fd, data, 0, data.length) count += data.length catch e console.log 'Error writing data chunk to '+tmppath+': '+e count = -1 res.on 'end',() -> fs.closeSync(fd) if count < 0 return fix_cache cache,ix+1 if count < length console.log 'Warning: read '+count+'/'+length+' bytes for '+file.url+' - discarding' try fs.unlinkSync tmppath catch e ; # ignore return fix_cache cache,ix+1 else console.log 'OK: read '+count+' bytes' oldpath = path + '.cb_old' # move old file if present if fs.existsSync path try # remove old old file if present fs.unlinkSync oldpath catch e ;# ignore try fs.renameSync path,oldpath catch e console.log 'Error renaming old cache file '+path+': '+e # move new file try fs.renameSync tmppath,path # done! try fs.unlinkSync oldpath catch e ; # ignore file.path = path if lastmod? then file.lastmod = lastmod if length? then file.length = length catch e console.log 'Error renaming new cache file '+tmppath+' to '+path+': '+e # new/updated html file? check for manifest! # note, not needed old files should all appear after 'needed' files; this should include previously downloaded manifest, etc. check_html_file cache,ix,file # next... check_appcache cache,file fix_cache cache,ix+1 req.on 'error',(e) -> console.log 'Error getting file '+file.url+': '+e fix_cache cache,ix+1 fix_cache cache,0 # TODO download icons and non-hidden files #req = http.get "http://www.google.com/index.html", (res) -> # console.log "Got response: " + res.statusCode #req.on 'error', (e) -> # console.log "Got error: " + e.message
100858
# coffee-script version of cache builder https = require 'https' http = require 'http' fs = require 'fs' xml2js = require 'xml2js' parse_url = (require 'url').parse resolve_url = (require 'url').resolve if process.argv.length<3 console.log 'usage: coffee cb.coffee <KIOSK-ATOM-FILE>' process.exit -1 # devices cofig devicesfn = "devices.json" console.log "read devices from #{devicesfn}" devicesin = fs.readFileSync devicesfn,'utf8' try devices = JSON.parse devicesin catch err console.log "Error parsing JSON from #{devicesfn}: #{err.message}" process.exit -1 # mimetypes defaults mimetypesinfn = "mimetypes-in.json" mimetypesfn = "mimetypes.json" console.log "read default mimetypes from #{mimetypesinfn}" mimetypesin = fs.readFileSync mimetypesinfn,'utf8' try mimetypes = JSON.parse mimetypesin catch err console.log "Error parsing JSON from #{mimetypesinfn}: #{err.message}" process.exit -1 # built-in mimetypes for mt,mtinfo of mimetypes console.log "Check default mimetype #{mt}" if not mtinfo.compat? mtinfo.compat = {} exclusive = false for dt,dtinfo of devices if dtinfo.supportsMimeExclusive? and dtinfo.supportsMimeExclusive.indexOf(mt) >= 0 exclusive = true for dt,dtinfo of devices #console.log "- against device #{dt}" dtcompat = {} if dtinfo.userAgentPattern? dtcompat.userAgentPattern = dtinfo.userAgentPattern if dtinfo.supportsMimeExclusive? and dtinfo.supportsMimeExclusive.indexOf(mt) >= 0 dtcompat.builtin = true else if dtinfo.supportsMime? and dtinfo.supportsMime.indexOf(mt) >= 0 dtcompat.builtin = true else if not dtinfo.optionalSupportsMime? or dtinfo.optionalSupportsMime.indexOf(mt) < 0 dtcompat.builtin = false # undefined = maybe / optional if exclusive dtcompat.appsComplete = true dtcompat.apps = [] mtinfo.compat[dt] = dtcompat console.log "Write initial mimetypes to #{mimetypesfn}" fs.writeFileSync mimetypesfn,JSON.stringify mimetypes # process atom file... atomfn = process.argv[2] parser = new xml2js.Parser() # is file hidden is_hidden = (entry) -> #console.dir entry for cs in entry.category ? [] when cs.$.scheme == 'visibility' and cs.$.term == 'hidden' return true return false # read main atom file console.log 'read '+atomfn data = fs.readFileSync atomfn, 'utf8' console.log 'read '+data.length+' bytes' # try reading shorturls.json shorturls = [] shorturlsfn = 'shorturls.json' try shorturlsdata = fs.readFileSync shorturlsfn,'utf8' shorturls = JSON.parse shorturlsdata catch e console.log 'could not read '+shorturlsfn+': '+e # try reading cache.json cache = {} cachefn = 'cache.json' try cachedata = fs.readFileSync cachefn,'utf8' cache = JSON.parse cachedata catch e console.log 'could not read '+cachefn+': '+e # make one shorturl add_shorturl = (shorturls,url) -> #console.log 'shorturl for '+url sus = for su in shorturls when su.url == url su.shorturl ? '' if sus.length == 0 # work out shorturl later shorturls.push { url: url } get_feedurl = (feed) -> feedurl = for link in feed.link when link.$.rel == 'self' link.$.href if feedurl.length < 1 console.log 'No self link found - cannot work out shorturls' process.exit -1 return feedurl[0] get_baseurl = (feed) -> baseurl = get_feedurl feed ix = baseurl.lastIndexOf '/' baseurl = baseurl.slice 0,ix+1 console.log 'Base URL = '+baseurl return baseurl # your google shortener API key?! API_KEY = '<KEY>' # app-defined mimetypes... make_mimetypes = (feed,mimetypes) -> console.log "make_mimetypes..." for appentry in feed.entry title = appentry.title[0] requires = for cat in appentry.category ? [] when cat.$.scheme == 'requires-device' and cat.$.term? cat.$.term supports = for cat in appentry.category ? [] when cat.$.scheme == 'supports-mime-type' and cat.$.term? { mime: cat.$.term, label: cat.$.label ?= cat.$.term } exclusive = for cat in appentry.category ? [] when cat.$.scheme == 'supports-mime-type-exclusive' and cat.$.term? cat.$.term appurls = for link in appentry.link ? [] when link.$.rel == 'enclosure' and link.$.href? link.$.href for device in requires for support in supports mt = support.mime if not mimetypes[mt]? mimetypes[mt] = { } mtinfo = mimetypes[mt] if support.label? and (not mtinfo.label? or mtinfo.label==mt) mtinfo.label = support.label # icon iconurls = for link in appentry.link ? [] when link.$.rel == 'alternate' and link.$.type? and link.$.href? and /^image/.test link.$.type link.$.href if iconurls.length > 0 and not mtinfo.icon? mtinfo.icon = iconurls[0] if not mtinfo.compat? mtinfo.compat = {} if not mtinfo.compat[device]? mtinfo.compat[device] = {} dtcompat = mtinfo.compat[device] if not dtcompat.userAgentPattern? and devices[device]?.userAgentPattern? dtcompat.userAgentPattern = devices[device].userAgentPattern if exclusive.length > 0 dtcompat.appsComplete = true if not dtcompat.apps? dtcompat.apps = [] for appurl in appurls dtcompat.apps.push { name: title, url: appurl } # shorturl for each make_shorturls = (feed,shorturls) -> console.log 'make_shorturls...' # campaignids... campaignids = for cat in feed.category ? [] when cat.$.scheme == 'campaign' and cat.$.term? cat.$.term campaignsuffix = for cid in campaignids '&c='+encodeURIComponent(cid) campaignsuffix.push '' # atom url -> get url baseurl = get_baseurl feed # .html?? .php for now! geturl = baseurl+'get.php' # request a short-url for internet kiosk view feedurl =get_feedurl feed kioskurl = baseurl+'index.html?f='+encodeURIComponent(feedurl) url = geturl+'?u='+encodeURIComponent(kioskurl)+'&t='+encodeURIComponent("Kiosk View") mimeparam = '&m='+encodeURIComponent('text/html') for cs in campaignsuffix add_shorturl shorturls,url+mimeparam+cs # qr flag add_shorturl shorturls,url+mimeparam+cs+'&qr' # device is now sniffed from agent only # work out URLs to be shortened # get.html?u=URL&t=TITLE[&m=MIMETYPE] # each entry... for entry in feed.entry when not is_hidden entry title = entry.title[0] # each enclosure for link in entry.link ?= [] when link.$.rel == 'enclosure' fileurl = link.$.href mime = link.$.type url = geturl+'?u='+encodeURIComponent(fileurl)+'&t='+encodeURIComponent(title) mimeparam = if mime? then '&m='+encodeURIComponent(mime) else '' for cs in campaignsuffix add_shorturl shorturls,url+mimeparam+cs # qr flag add_shorturl shorturls,url+mimeparam+cs+'&qr' # device is now sniffed from agent only add_fileurl = (url, fileurls) -> #console.log "check #{url}" # not sure why indexOf doesn't seem to match it us = for u in fileurls when u == url u if not us? or us.length == 0 #console.log 'add '+url+' to fileurls' fileurls.push url fix_relative_url = (url,path) -> resolve_url url, path # cache entry for each make_cache = (feed,cache) -> fileurls = [] for entry in feed.entry #console.dir entry hidden = is_hidden entry # atom enclosures for link in entry.link when link.$.href? and (link.$.rel == 'alternate' or not hidden) add_fileurl (fix_relative_url cache.baseurl, link.$.href), fileurls # media-rss media:thumbnail for thumbnail in (entry['media:thumbnail'] ? []) when thumbnail.$.url? add_fileurl (fix_relative_url cache.baseurl, thumbnail.$.url), fileurls console.dir fileurls oldfiles = cache.files ? [] cache.files = [] for file in oldfiles file.needed = false # does the file exist? if file.path? fileok = false try st = fs.statSync file.path if st.isFile() fileok = true else console.log 'old cache path not file: '+file.path catch e console.log 'old cache file not found: '+file.path if not fileok # doesn't exist, presumably delete file.path delete file.length delete file.lastmod for fileurl in fileurls file = { url: fileurl } oldfile = for f in oldfiles when f.url == fileurl f if oldfile.length > 0 file = oldfile[0] file.needed = true cache.files.push file #console.log "Add to cache #{file.url}" # un-needed files in cache? for oldfile in oldfiles when oldfile.path? and not oldfile.needed present = for f in cache.files when f.url == oldfile.url f if present.length==0 cache.files.push oldfile else console.log "Discard duplicate file cache entry #{oldfile.url}" get_filename_for_component = (h) -> if h=='' return '_' h = decodeURIComponent h return h.replace("~","_") # is that enough?? # get local cache path for an URL - like java cacheing, # maps domain name elements and path elements to folders get_cache_path = (url) -> url = parse_url url # hostname, port, path (includes query), hash hs = if url.hostname? then url.hostname.split '.' else [] # reverse non-IP order number = /^[0-9]+$/ ns = 0 for h in hs when number.test h ns++ if ns != hs.length hs.reverse # normalise domain name to lower case hs = for h in hs String(h).toLowerCase() # ignore port for now! ps = if url.path? then url.path.split '/' else [] # leading /? if ps.length>1 and ps[0]=='' ps.shift() hs = ["cache"].concat hs,ps # make safe filenames hs = for h in hs get_filename_for_component h path = hs.join '/' return path doneShorturls = false doneCache = false # may be present unneeded, or not add_cache_url = (cache,url,appcache) -> for f in cache.files when f.url == url if appcache? f.appcache = true if f.needed console.log "URL already needed: #{url}" return console.log "URL present, now needed: #{url}" f.needed = true return file = { url: url, needed: true } console.log "Add url #{url}" cache.files.push file check_appcache = (cache,file) -> if not file.path? return si = file.path.lastIndexOf '/' ei = file.path.lastIndexOf '.' extn = if ei<0 or ei<si then '' else file.path.substring(ei+1) if extn=='appcache' console.log "check appcache file #{file.url}" try appcache = fs.readFileSync file.path,{encoding:'utf8'} lines = appcache.split '\n' lines = for l in lines when l.trim().indexOf('#')!=0 and l.trim().length>0 l.trim() if lines.length<=0 console.log "Empty appcache manifest #{file.url}" return if lines[0]!='CACHE MANIFEST' console.log "Bad appcache manifest #{file.url}; first line #{lines[0]}" section = "CACHE:" for l,i in lines when i>0 if l=="CACHE:" or l=="SETTINGS:" or l=="NETWORK:" section = l else if section=="CACHE:" url = fix_relative_url file.url,l console.log "Found manifest entry #{l} -> #{url}" add_cache_url cache,url catch err console.log "Error checking appcache file #{file.path}: #{err}" check_html_file = (cache,ix,file) -> si = file.path.lastIndexOf '/' ei = file.path.lastIndexOf '.' extn = if ei<0 or ei<si then '' else file.path.substring(ei+1) if extn=='htm' or extn=='html' or extn=='xhtml' try html = fs.readFileSync file.path,{encoding:'utf8'} hi = html.indexOf '<html ' hi2 = html.indexOf '>',hi mi = html.indexOf ' manifest="', hi mi2 = html.indexOf '"', mi+11 if mi>=0 and mi2>=mi and mi2<hi2 manifest = (html.substring mi+11,mi2) # make absolute, schedule for download and check manifesturl = fix_relative_url file.url,manifest console.log "Found html manifest #{manifest} in #{file.url} -> #{manifesturl}" # set appcache flag add_cache_url cache,manifesturl,true catch err console.log "Error checking html file: #{err}" # parse file(s) and call worker(s) parser.parseString data,(err,result) -> if err console.log 'Error parsing '+atomfn+': '+err process.exit -1 feed = result.feed console.log 'Feed '+feed.title+' ('+feed.id+')' make_mimetypes feed,mimetypes console.log "write mimetypes to #{mimetypesfn}" fs.writeFileSync mimetypesfn,JSON.stringify mimetypes make_shorturls feed,shorturls fix_shorturls = (shorturls,i) -> if i >= shorturls.length # done console.log 'write shorturls.json' fs.writeFileSync shorturlsfn,JSON.stringify shorturls doneShorturls = true if doneShorturls and doneCache process.exit 0 else su = shorturls[i] if su.shorturl == undefined # see https://developers.google.com/url-shortener/v1/getting_started # POST application/json {"longUrl":"XXX"} -> # https://www.googleapis.com/urlshortener/v1/url # { "kind": "urlshortener#url", "id": "http://goo.gl/XXXX", # "longUrl": "XXX" } console.log 'Shorten '+su.url req = {longUrl: su.url} reqs = JSON.stringify req url = '/urlshortener/v1/url' if API_KEY? url = url+"?key="+API_KEY options = hostname: 'www.googleapis.com' path: url method: 'POST' headers: { 'content-type': 'application/json' } hreq = https.request options, (res) -> if res.statusCode != 200 console.log 'got shortener response '+res.statusCode process.exit -1 res.setEncoding 'utf8' data = '' res.on 'data',(chunk) -> #console.log 'shortener response: '+chunk data = data+chunk res.on 'end',()-> jres = JSON.parse data su.shorturl = jres.id console.log 'Shortened to '+su.shorturl # recurse fix_shorturls shorturls,i+1 hreq.on 'error',(e) -> console.log 'Error shortening url: '+e process.exit -1 hreq.end reqs #console.log 'sent '+reqs else # recurse fix_shorturls shorturls,i+1 fix_shorturls shorturls,0 # download icons and visible enclosures, populating cache.json baseurl = get_baseurl feed cache.baseurl = baseurl make_cache feed,cache fix_cache = (cache,ix) -> if ix >= cache.files.length # done! console.log 'write cache.json' fs.writeFileSync cachefn,JSON.stringify cache doneCache = true if doneShorturls and doneCache process.exit 0 else file = cache.files[ix] #console.log 'fix_cache '+ix+': '+file.url+', was '+file.path if file.needed and file.url.indexOf( cache.baseurl )==0 file.path = file.url.substring (cache.baseurl.length) console.log "local file #{file.url} -> #{file.path}" check_appcache cache,file check_html_file cache,ix,file fix_cache cache,ix+1 else if file.needed and file.path? check_file_modified cache,ix,file else if file.needed get_cache_file cache,ix,file else #check_appcache cache,file # not needed! fix_cache cache,ix+1 check_file_modified = (cache,ix,file) -> # if the local file exists and we have size and server last-modified, # try a head on the remote file with if-modified-since; # (prepare to) dump local copy if out of date # TODO if file.lastmod? console.log 'Check '+file.url url = parse_url file.url protocol = url.protocol ?= 'http' options = hostname: url.hostname port: url.port path: url.path auth: url.auth method: 'HEAD' headers: { 'if-modified-since': file.lastmod } pmodule = if protocol=='https' then https else http req = pmodule.request options,(res) -> res.on 'data',(data) -> ; # no op if res.statusCode == 304 console.log 'Not modified: '+file.url check_appcache cache,file fix_cache cache,ix+1 else console.log 'Check returned '+res.statusCode+'; assume modified' get_cache_file cache,ix,file req.on 'error',(e) -> console.log 'Error checking '+file.url+' ('+JSON.stringify( options )+'): '+e get_cache_file cache,ix,file req.end() else get_cache_file cache,ix,file get_cache_file = (cache,ix,file) -> # new local path = url mapped to folder hierarchy - domain name # in reverse order (ip forwards), port, path elements, # final filename+fragment+query path = file.path ? get_cache_path file.url #console.log 'new file path = '+path+' for '+file.url # check directory exists dir = '' ps = path.split '/' if ps.length>1 for i in [0..(ps.length-2)] dir = dir + (if i>0 then '/' else '') + ps[i] if !fs.existsSync(dir) fs.mkdirSync dir # if updated or missing attempt download, initially to temp file # and stash header last-modified and content-length url = parse_url file.url protocol = url.protocol ? 'http' options = method: 'GET' pmodule = if protocol=='https' then https else http console.log 'Download '+file.url req = pmodule.get file.url,(res) -> if res.statusCode != 200 console.log 'Error getting file '+file.url+', response '+res.statusCode fix_cache cache,ix+1 else # on success remove old file if present and link/rename new file lastmod = res.headers['last-modified'] length = res.headers['content-length'] tmppath = dir + (if dir!='' then '/' else '') + '.cb_download' try fd = fs.openSync(tmppath, 'w') catch e console.log 'Could not create tmpfile '+tmppath+': '+e return fix_cache cache,ix+1 count = 0; res.on 'data',(data) -> if count < 0 return #console.log 'got '+data.length+' bytes for '+file.url try fs.writeSync(fd, data, 0, data.length) count += data.length catch e console.log 'Error writing data chunk to '+tmppath+': '+e count = -1 res.on 'end',() -> fs.closeSync(fd) if count < 0 return fix_cache cache,ix+1 if count < length console.log 'Warning: read '+count+'/'+length+' bytes for '+file.url+' - discarding' try fs.unlinkSync tmppath catch e ; # ignore return fix_cache cache,ix+1 else console.log 'OK: read '+count+' bytes' oldpath = path + '.cb_old' # move old file if present if fs.existsSync path try # remove old old file if present fs.unlinkSync oldpath catch e ;# ignore try fs.renameSync path,oldpath catch e console.log 'Error renaming old cache file '+path+': '+e # move new file try fs.renameSync tmppath,path # done! try fs.unlinkSync oldpath catch e ; # ignore file.path = path if lastmod? then file.lastmod = lastmod if length? then file.length = length catch e console.log 'Error renaming new cache file '+tmppath+' to '+path+': '+e # new/updated html file? check for manifest! # note, not needed old files should all appear after 'needed' files; this should include previously downloaded manifest, etc. check_html_file cache,ix,file # next... check_appcache cache,file fix_cache cache,ix+1 req.on 'error',(e) -> console.log 'Error getting file '+file.url+': '+e fix_cache cache,ix+1 fix_cache cache,0 # TODO download icons and non-hidden files #req = http.get "http://www.google.com/index.html", (res) -> # console.log "Got response: " + res.statusCode #req.on 'error', (e) -> # console.log "Got error: " + e.message
true
# coffee-script version of cache builder https = require 'https' http = require 'http' fs = require 'fs' xml2js = require 'xml2js' parse_url = (require 'url').parse resolve_url = (require 'url').resolve if process.argv.length<3 console.log 'usage: coffee cb.coffee <KIOSK-ATOM-FILE>' process.exit -1 # devices cofig devicesfn = "devices.json" console.log "read devices from #{devicesfn}" devicesin = fs.readFileSync devicesfn,'utf8' try devices = JSON.parse devicesin catch err console.log "Error parsing JSON from #{devicesfn}: #{err.message}" process.exit -1 # mimetypes defaults mimetypesinfn = "mimetypes-in.json" mimetypesfn = "mimetypes.json" console.log "read default mimetypes from #{mimetypesinfn}" mimetypesin = fs.readFileSync mimetypesinfn,'utf8' try mimetypes = JSON.parse mimetypesin catch err console.log "Error parsing JSON from #{mimetypesinfn}: #{err.message}" process.exit -1 # built-in mimetypes for mt,mtinfo of mimetypes console.log "Check default mimetype #{mt}" if not mtinfo.compat? mtinfo.compat = {} exclusive = false for dt,dtinfo of devices if dtinfo.supportsMimeExclusive? and dtinfo.supportsMimeExclusive.indexOf(mt) >= 0 exclusive = true for dt,dtinfo of devices #console.log "- against device #{dt}" dtcompat = {} if dtinfo.userAgentPattern? dtcompat.userAgentPattern = dtinfo.userAgentPattern if dtinfo.supportsMimeExclusive? and dtinfo.supportsMimeExclusive.indexOf(mt) >= 0 dtcompat.builtin = true else if dtinfo.supportsMime? and dtinfo.supportsMime.indexOf(mt) >= 0 dtcompat.builtin = true else if not dtinfo.optionalSupportsMime? or dtinfo.optionalSupportsMime.indexOf(mt) < 0 dtcompat.builtin = false # undefined = maybe / optional if exclusive dtcompat.appsComplete = true dtcompat.apps = [] mtinfo.compat[dt] = dtcompat console.log "Write initial mimetypes to #{mimetypesfn}" fs.writeFileSync mimetypesfn,JSON.stringify mimetypes # process atom file... atomfn = process.argv[2] parser = new xml2js.Parser() # is file hidden is_hidden = (entry) -> #console.dir entry for cs in entry.category ? [] when cs.$.scheme == 'visibility' and cs.$.term == 'hidden' return true return false # read main atom file console.log 'read '+atomfn data = fs.readFileSync atomfn, 'utf8' console.log 'read '+data.length+' bytes' # try reading shorturls.json shorturls = [] shorturlsfn = 'shorturls.json' try shorturlsdata = fs.readFileSync shorturlsfn,'utf8' shorturls = JSON.parse shorturlsdata catch e console.log 'could not read '+shorturlsfn+': '+e # try reading cache.json cache = {} cachefn = 'cache.json' try cachedata = fs.readFileSync cachefn,'utf8' cache = JSON.parse cachedata catch e console.log 'could not read '+cachefn+': '+e # make one shorturl add_shorturl = (shorturls,url) -> #console.log 'shorturl for '+url sus = for su in shorturls when su.url == url su.shorturl ? '' if sus.length == 0 # work out shorturl later shorturls.push { url: url } get_feedurl = (feed) -> feedurl = for link in feed.link when link.$.rel == 'self' link.$.href if feedurl.length < 1 console.log 'No self link found - cannot work out shorturls' process.exit -1 return feedurl[0] get_baseurl = (feed) -> baseurl = get_feedurl feed ix = baseurl.lastIndexOf '/' baseurl = baseurl.slice 0,ix+1 console.log 'Base URL = '+baseurl return baseurl # your google shortener API key?! API_KEY = 'PI:KEY:<KEY>END_PI' # app-defined mimetypes... make_mimetypes = (feed,mimetypes) -> console.log "make_mimetypes..." for appentry in feed.entry title = appentry.title[0] requires = for cat in appentry.category ? [] when cat.$.scheme == 'requires-device' and cat.$.term? cat.$.term supports = for cat in appentry.category ? [] when cat.$.scheme == 'supports-mime-type' and cat.$.term? { mime: cat.$.term, label: cat.$.label ?= cat.$.term } exclusive = for cat in appentry.category ? [] when cat.$.scheme == 'supports-mime-type-exclusive' and cat.$.term? cat.$.term appurls = for link in appentry.link ? [] when link.$.rel == 'enclosure' and link.$.href? link.$.href for device in requires for support in supports mt = support.mime if not mimetypes[mt]? mimetypes[mt] = { } mtinfo = mimetypes[mt] if support.label? and (not mtinfo.label? or mtinfo.label==mt) mtinfo.label = support.label # icon iconurls = for link in appentry.link ? [] when link.$.rel == 'alternate' and link.$.type? and link.$.href? and /^image/.test link.$.type link.$.href if iconurls.length > 0 and not mtinfo.icon? mtinfo.icon = iconurls[0] if not mtinfo.compat? mtinfo.compat = {} if not mtinfo.compat[device]? mtinfo.compat[device] = {} dtcompat = mtinfo.compat[device] if not dtcompat.userAgentPattern? and devices[device]?.userAgentPattern? dtcompat.userAgentPattern = devices[device].userAgentPattern if exclusive.length > 0 dtcompat.appsComplete = true if not dtcompat.apps? dtcompat.apps = [] for appurl in appurls dtcompat.apps.push { name: title, url: appurl } # shorturl for each make_shorturls = (feed,shorturls) -> console.log 'make_shorturls...' # campaignids... campaignids = for cat in feed.category ? [] when cat.$.scheme == 'campaign' and cat.$.term? cat.$.term campaignsuffix = for cid in campaignids '&c='+encodeURIComponent(cid) campaignsuffix.push '' # atom url -> get url baseurl = get_baseurl feed # .html?? .php for now! geturl = baseurl+'get.php' # request a short-url for internet kiosk view feedurl =get_feedurl feed kioskurl = baseurl+'index.html?f='+encodeURIComponent(feedurl) url = geturl+'?u='+encodeURIComponent(kioskurl)+'&t='+encodeURIComponent("Kiosk View") mimeparam = '&m='+encodeURIComponent('text/html') for cs in campaignsuffix add_shorturl shorturls,url+mimeparam+cs # qr flag add_shorturl shorturls,url+mimeparam+cs+'&qr' # device is now sniffed from agent only # work out URLs to be shortened # get.html?u=URL&t=TITLE[&m=MIMETYPE] # each entry... for entry in feed.entry when not is_hidden entry title = entry.title[0] # each enclosure for link in entry.link ?= [] when link.$.rel == 'enclosure' fileurl = link.$.href mime = link.$.type url = geturl+'?u='+encodeURIComponent(fileurl)+'&t='+encodeURIComponent(title) mimeparam = if mime? then '&m='+encodeURIComponent(mime) else '' for cs in campaignsuffix add_shorturl shorturls,url+mimeparam+cs # qr flag add_shorturl shorturls,url+mimeparam+cs+'&qr' # device is now sniffed from agent only add_fileurl = (url, fileurls) -> #console.log "check #{url}" # not sure why indexOf doesn't seem to match it us = for u in fileurls when u == url u if not us? or us.length == 0 #console.log 'add '+url+' to fileurls' fileurls.push url fix_relative_url = (url,path) -> resolve_url url, path # cache entry for each make_cache = (feed,cache) -> fileurls = [] for entry in feed.entry #console.dir entry hidden = is_hidden entry # atom enclosures for link in entry.link when link.$.href? and (link.$.rel == 'alternate' or not hidden) add_fileurl (fix_relative_url cache.baseurl, link.$.href), fileurls # media-rss media:thumbnail for thumbnail in (entry['media:thumbnail'] ? []) when thumbnail.$.url? add_fileurl (fix_relative_url cache.baseurl, thumbnail.$.url), fileurls console.dir fileurls oldfiles = cache.files ? [] cache.files = [] for file in oldfiles file.needed = false # does the file exist? if file.path? fileok = false try st = fs.statSync file.path if st.isFile() fileok = true else console.log 'old cache path not file: '+file.path catch e console.log 'old cache file not found: '+file.path if not fileok # doesn't exist, presumably delete file.path delete file.length delete file.lastmod for fileurl in fileurls file = { url: fileurl } oldfile = for f in oldfiles when f.url == fileurl f if oldfile.length > 0 file = oldfile[0] file.needed = true cache.files.push file #console.log "Add to cache #{file.url}" # un-needed files in cache? for oldfile in oldfiles when oldfile.path? and not oldfile.needed present = for f in cache.files when f.url == oldfile.url f if present.length==0 cache.files.push oldfile else console.log "Discard duplicate file cache entry #{oldfile.url}" get_filename_for_component = (h) -> if h=='' return '_' h = decodeURIComponent h return h.replace("~","_") # is that enough?? # get local cache path for an URL - like java cacheing, # maps domain name elements and path elements to folders get_cache_path = (url) -> url = parse_url url # hostname, port, path (includes query), hash hs = if url.hostname? then url.hostname.split '.' else [] # reverse non-IP order number = /^[0-9]+$/ ns = 0 for h in hs when number.test h ns++ if ns != hs.length hs.reverse # normalise domain name to lower case hs = for h in hs String(h).toLowerCase() # ignore port for now! ps = if url.path? then url.path.split '/' else [] # leading /? if ps.length>1 and ps[0]=='' ps.shift() hs = ["cache"].concat hs,ps # make safe filenames hs = for h in hs get_filename_for_component h path = hs.join '/' return path doneShorturls = false doneCache = false # may be present unneeded, or not add_cache_url = (cache,url,appcache) -> for f in cache.files when f.url == url if appcache? f.appcache = true if f.needed console.log "URL already needed: #{url}" return console.log "URL present, now needed: #{url}" f.needed = true return file = { url: url, needed: true } console.log "Add url #{url}" cache.files.push file check_appcache = (cache,file) -> if not file.path? return si = file.path.lastIndexOf '/' ei = file.path.lastIndexOf '.' extn = if ei<0 or ei<si then '' else file.path.substring(ei+1) if extn=='appcache' console.log "check appcache file #{file.url}" try appcache = fs.readFileSync file.path,{encoding:'utf8'} lines = appcache.split '\n' lines = for l in lines when l.trim().indexOf('#')!=0 and l.trim().length>0 l.trim() if lines.length<=0 console.log "Empty appcache manifest #{file.url}" return if lines[0]!='CACHE MANIFEST' console.log "Bad appcache manifest #{file.url}; first line #{lines[0]}" section = "CACHE:" for l,i in lines when i>0 if l=="CACHE:" or l=="SETTINGS:" or l=="NETWORK:" section = l else if section=="CACHE:" url = fix_relative_url file.url,l console.log "Found manifest entry #{l} -> #{url}" add_cache_url cache,url catch err console.log "Error checking appcache file #{file.path}: #{err}" check_html_file = (cache,ix,file) -> si = file.path.lastIndexOf '/' ei = file.path.lastIndexOf '.' extn = if ei<0 or ei<si then '' else file.path.substring(ei+1) if extn=='htm' or extn=='html' or extn=='xhtml' try html = fs.readFileSync file.path,{encoding:'utf8'} hi = html.indexOf '<html ' hi2 = html.indexOf '>',hi mi = html.indexOf ' manifest="', hi mi2 = html.indexOf '"', mi+11 if mi>=0 and mi2>=mi and mi2<hi2 manifest = (html.substring mi+11,mi2) # make absolute, schedule for download and check manifesturl = fix_relative_url file.url,manifest console.log "Found html manifest #{manifest} in #{file.url} -> #{manifesturl}" # set appcache flag add_cache_url cache,manifesturl,true catch err console.log "Error checking html file: #{err}" # parse file(s) and call worker(s) parser.parseString data,(err,result) -> if err console.log 'Error parsing '+atomfn+': '+err process.exit -1 feed = result.feed console.log 'Feed '+feed.title+' ('+feed.id+')' make_mimetypes feed,mimetypes console.log "write mimetypes to #{mimetypesfn}" fs.writeFileSync mimetypesfn,JSON.stringify mimetypes make_shorturls feed,shorturls fix_shorturls = (shorturls,i) -> if i >= shorturls.length # done console.log 'write shorturls.json' fs.writeFileSync shorturlsfn,JSON.stringify shorturls doneShorturls = true if doneShorturls and doneCache process.exit 0 else su = shorturls[i] if su.shorturl == undefined # see https://developers.google.com/url-shortener/v1/getting_started # POST application/json {"longUrl":"XXX"} -> # https://www.googleapis.com/urlshortener/v1/url # { "kind": "urlshortener#url", "id": "http://goo.gl/XXXX", # "longUrl": "XXX" } console.log 'Shorten '+su.url req = {longUrl: su.url} reqs = JSON.stringify req url = '/urlshortener/v1/url' if API_KEY? url = url+"?key="+API_KEY options = hostname: 'www.googleapis.com' path: url method: 'POST' headers: { 'content-type': 'application/json' } hreq = https.request options, (res) -> if res.statusCode != 200 console.log 'got shortener response '+res.statusCode process.exit -1 res.setEncoding 'utf8' data = '' res.on 'data',(chunk) -> #console.log 'shortener response: '+chunk data = data+chunk res.on 'end',()-> jres = JSON.parse data su.shorturl = jres.id console.log 'Shortened to '+su.shorturl # recurse fix_shorturls shorturls,i+1 hreq.on 'error',(e) -> console.log 'Error shortening url: '+e process.exit -1 hreq.end reqs #console.log 'sent '+reqs else # recurse fix_shorturls shorturls,i+1 fix_shorturls shorturls,0 # download icons and visible enclosures, populating cache.json baseurl = get_baseurl feed cache.baseurl = baseurl make_cache feed,cache fix_cache = (cache,ix) -> if ix >= cache.files.length # done! console.log 'write cache.json' fs.writeFileSync cachefn,JSON.stringify cache doneCache = true if doneShorturls and doneCache process.exit 0 else file = cache.files[ix] #console.log 'fix_cache '+ix+': '+file.url+', was '+file.path if file.needed and file.url.indexOf( cache.baseurl )==0 file.path = file.url.substring (cache.baseurl.length) console.log "local file #{file.url} -> #{file.path}" check_appcache cache,file check_html_file cache,ix,file fix_cache cache,ix+1 else if file.needed and file.path? check_file_modified cache,ix,file else if file.needed get_cache_file cache,ix,file else #check_appcache cache,file # not needed! fix_cache cache,ix+1 check_file_modified = (cache,ix,file) -> # if the local file exists and we have size and server last-modified, # try a head on the remote file with if-modified-since; # (prepare to) dump local copy if out of date # TODO if file.lastmod? console.log 'Check '+file.url url = parse_url file.url protocol = url.protocol ?= 'http' options = hostname: url.hostname port: url.port path: url.path auth: url.auth method: 'HEAD' headers: { 'if-modified-since': file.lastmod } pmodule = if protocol=='https' then https else http req = pmodule.request options,(res) -> res.on 'data',(data) -> ; # no op if res.statusCode == 304 console.log 'Not modified: '+file.url check_appcache cache,file fix_cache cache,ix+1 else console.log 'Check returned '+res.statusCode+'; assume modified' get_cache_file cache,ix,file req.on 'error',(e) -> console.log 'Error checking '+file.url+' ('+JSON.stringify( options )+'): '+e get_cache_file cache,ix,file req.end() else get_cache_file cache,ix,file get_cache_file = (cache,ix,file) -> # new local path = url mapped to folder hierarchy - domain name # in reverse order (ip forwards), port, path elements, # final filename+fragment+query path = file.path ? get_cache_path file.url #console.log 'new file path = '+path+' for '+file.url # check directory exists dir = '' ps = path.split '/' if ps.length>1 for i in [0..(ps.length-2)] dir = dir + (if i>0 then '/' else '') + ps[i] if !fs.existsSync(dir) fs.mkdirSync dir # if updated or missing attempt download, initially to temp file # and stash header last-modified and content-length url = parse_url file.url protocol = url.protocol ? 'http' options = method: 'GET' pmodule = if protocol=='https' then https else http console.log 'Download '+file.url req = pmodule.get file.url,(res) -> if res.statusCode != 200 console.log 'Error getting file '+file.url+', response '+res.statusCode fix_cache cache,ix+1 else # on success remove old file if present and link/rename new file lastmod = res.headers['last-modified'] length = res.headers['content-length'] tmppath = dir + (if dir!='' then '/' else '') + '.cb_download' try fd = fs.openSync(tmppath, 'w') catch e console.log 'Could not create tmpfile '+tmppath+': '+e return fix_cache cache,ix+1 count = 0; res.on 'data',(data) -> if count < 0 return #console.log 'got '+data.length+' bytes for '+file.url try fs.writeSync(fd, data, 0, data.length) count += data.length catch e console.log 'Error writing data chunk to '+tmppath+': '+e count = -1 res.on 'end',() -> fs.closeSync(fd) if count < 0 return fix_cache cache,ix+1 if count < length console.log 'Warning: read '+count+'/'+length+' bytes for '+file.url+' - discarding' try fs.unlinkSync tmppath catch e ; # ignore return fix_cache cache,ix+1 else console.log 'OK: read '+count+' bytes' oldpath = path + '.cb_old' # move old file if present if fs.existsSync path try # remove old old file if present fs.unlinkSync oldpath catch e ;# ignore try fs.renameSync path,oldpath catch e console.log 'Error renaming old cache file '+path+': '+e # move new file try fs.renameSync tmppath,path # done! try fs.unlinkSync oldpath catch e ; # ignore file.path = path if lastmod? then file.lastmod = lastmod if length? then file.length = length catch e console.log 'Error renaming new cache file '+tmppath+' to '+path+': '+e # new/updated html file? check for manifest! # note, not needed old files should all appear after 'needed' files; this should include previously downloaded manifest, etc. check_html_file cache,ix,file # next... check_appcache cache,file fix_cache cache,ix+1 req.on 'error',(e) -> console.log 'Error getting file '+file.url+': '+e fix_cache cache,ix+1 fix_cache cache,0 # TODO download icons and non-hidden files #req = http.get "http://www.google.com/index.html", (res) -> # console.log "Got response: " + res.statusCode #req.on 'error', (e) -> # console.log "Got error: " + e.message
[ { "context": "$scope.submitterParams\n translatedKey = \"submitter[#{key}]\"\n $scope.submissionParams[tra", "end": 1001, "score": 0.7614695429801941, "start": 995, "tag": "KEY", "value": "submit" }, { "context": "bmitterParams\n translatedKey = \"submitter[#{key}]\"\n $scope.submissionParams[translatedKey]", "end": 1012, "score": 0.9327040910720825, "start": 1005, "tag": "KEY", "value": "#{key}]" } ]
frontend/src/controllers/private/teacher/results.coffee
greysteil/evaluator
1
angular.module 'evaluator' .controller 'TeacherResultsController', ($scope, ProjectSubmissionsResource, CoursesResource, CourseProjectsResource, Pagination, Submission, defaultPageSize, deletedSubmissionIds) -> $scope.loadingSubmissions = false # Data used by the search form $scope.formData = {} $scope.searchData = name: '' email: '' guc_prefix: '' guc_suffix: '' team: '' # data used for searching for submissions $scope.submitterParams = name: null email: null guc_prefix: null guc_suffix: null team: null $scope.submissionParams = project_id: null "submitter[name]": null "submitter[email]": null "submitter[guc_prefix]": null "submitter[guc_suffix]": null "submitter[team]": null updateSubmitterParams = -> for key, value of $scope.submitterParams translatedKey = "submitter[#{key}]" $scope.submissionParams[translatedKey] = value return $scope.submissionClasses = ['submission-accent-one', 'submission-accent-two', 'submission-accent-three'] $scope.submissions = [] deletedSubmissionCallback = (id) -> deletedSubmissionIds.push id _.remove $scope.submissions, (submission) -> submission.id is id $scope.$watch 'searchData', (newValue) -> changed = false for key, value of newValue oldParamValue = $scope.submitterParams[key] if value && value.length > 0 $scope.submitterParams[key] = value else $scope.submitterParams[key] = null changed |= oldParamValue != $scope.submitterParams[key] updateSubmitterParams() $scope.reload() if changed return , true $scope.courseSearch = (nameQuery) -> CoursesResource.query({ name: nameQuery, page: 1, page_size: 100 }).$promise.then (data) -> data.courses $scope.projectSearch = (nameQuery, course) -> CourseProjectsResource.query({ course_id: course.id, page: 1, page_size: 100, name: nameQuery }).$promise.then (data) -> data.projects submissionFactory = (data) -> return new Submission data, deletedSubmissionCallback addSubmissionsCallback = (newSubmissions) -> submissions = _.filter newSubmissions, (s) -> s.id not in deletedSubmissionIds args = [0, $scope.submissions.length].concat submissions $scope.submissions.splice.apply $scope.submissions, args $scope.submissionsPagination = new Pagination ProjectSubmissionsResource, 'submissions', $scope.submissionParams, submissionFactory, defaultPageSize $scope.reload = -> return if $scope.loadingSubmissions $scope.loadingSubmissions = true $scope.submissionsPagination.reload().then (submissions) -> $scope.loadingSubmissions = false addSubmissionsCallback submissions loadSubmissionsPage = (page) -> $scope.loadingSubmissions = true $scope.submissionsPagination.page(page).then (submissions) -> $scope.loadingSubmissions = false $scope.currentPage = page addSubmissionsCallback submissions $scope.currentPage = 1 $scope.selectProject = (project) -> if project $scope.currentPage = 1 $scope.submissionParams.project_id = project.id $scope.reload() else $scope.submissionParams.project_id = null $scope.backDisabled = -> $scope.currentPage is 1 $scope.nextDisabled = -> $scope.currentPage >= $scope.submissionsPagination.totalPages $scope.next = -> if not $scope.nextDisabled() loadSubmissionsPage($scope.currentPage + 1) $scope.back = -> if not $scope.backDisabled() loadSubmissionsPage($scope.currentPage - 1)
124081
angular.module 'evaluator' .controller 'TeacherResultsController', ($scope, ProjectSubmissionsResource, CoursesResource, CourseProjectsResource, Pagination, Submission, defaultPageSize, deletedSubmissionIds) -> $scope.loadingSubmissions = false # Data used by the search form $scope.formData = {} $scope.searchData = name: '' email: '' guc_prefix: '' guc_suffix: '' team: '' # data used for searching for submissions $scope.submitterParams = name: null email: null guc_prefix: null guc_suffix: null team: null $scope.submissionParams = project_id: null "submitter[name]": null "submitter[email]": null "submitter[guc_prefix]": null "submitter[guc_suffix]": null "submitter[team]": null updateSubmitterParams = -> for key, value of $scope.submitterParams translatedKey = "<KEY>ter[<KEY>" $scope.submissionParams[translatedKey] = value return $scope.submissionClasses = ['submission-accent-one', 'submission-accent-two', 'submission-accent-three'] $scope.submissions = [] deletedSubmissionCallback = (id) -> deletedSubmissionIds.push id _.remove $scope.submissions, (submission) -> submission.id is id $scope.$watch 'searchData', (newValue) -> changed = false for key, value of newValue oldParamValue = $scope.submitterParams[key] if value && value.length > 0 $scope.submitterParams[key] = value else $scope.submitterParams[key] = null changed |= oldParamValue != $scope.submitterParams[key] updateSubmitterParams() $scope.reload() if changed return , true $scope.courseSearch = (nameQuery) -> CoursesResource.query({ name: nameQuery, page: 1, page_size: 100 }).$promise.then (data) -> data.courses $scope.projectSearch = (nameQuery, course) -> CourseProjectsResource.query({ course_id: course.id, page: 1, page_size: 100, name: nameQuery }).$promise.then (data) -> data.projects submissionFactory = (data) -> return new Submission data, deletedSubmissionCallback addSubmissionsCallback = (newSubmissions) -> submissions = _.filter newSubmissions, (s) -> s.id not in deletedSubmissionIds args = [0, $scope.submissions.length].concat submissions $scope.submissions.splice.apply $scope.submissions, args $scope.submissionsPagination = new Pagination ProjectSubmissionsResource, 'submissions', $scope.submissionParams, submissionFactory, defaultPageSize $scope.reload = -> return if $scope.loadingSubmissions $scope.loadingSubmissions = true $scope.submissionsPagination.reload().then (submissions) -> $scope.loadingSubmissions = false addSubmissionsCallback submissions loadSubmissionsPage = (page) -> $scope.loadingSubmissions = true $scope.submissionsPagination.page(page).then (submissions) -> $scope.loadingSubmissions = false $scope.currentPage = page addSubmissionsCallback submissions $scope.currentPage = 1 $scope.selectProject = (project) -> if project $scope.currentPage = 1 $scope.submissionParams.project_id = project.id $scope.reload() else $scope.submissionParams.project_id = null $scope.backDisabled = -> $scope.currentPage is 1 $scope.nextDisabled = -> $scope.currentPage >= $scope.submissionsPagination.totalPages $scope.next = -> if not $scope.nextDisabled() loadSubmissionsPage($scope.currentPage + 1) $scope.back = -> if not $scope.backDisabled() loadSubmissionsPage($scope.currentPage - 1)
true
angular.module 'evaluator' .controller 'TeacherResultsController', ($scope, ProjectSubmissionsResource, CoursesResource, CourseProjectsResource, Pagination, Submission, defaultPageSize, deletedSubmissionIds) -> $scope.loadingSubmissions = false # Data used by the search form $scope.formData = {} $scope.searchData = name: '' email: '' guc_prefix: '' guc_suffix: '' team: '' # data used for searching for submissions $scope.submitterParams = name: null email: null guc_prefix: null guc_suffix: null team: null $scope.submissionParams = project_id: null "submitter[name]": null "submitter[email]": null "submitter[guc_prefix]": null "submitter[guc_suffix]": null "submitter[team]": null updateSubmitterParams = -> for key, value of $scope.submitterParams translatedKey = "PI:KEY:<KEY>END_PIter[PI:KEY:<KEY>END_PI" $scope.submissionParams[translatedKey] = value return $scope.submissionClasses = ['submission-accent-one', 'submission-accent-two', 'submission-accent-three'] $scope.submissions = [] deletedSubmissionCallback = (id) -> deletedSubmissionIds.push id _.remove $scope.submissions, (submission) -> submission.id is id $scope.$watch 'searchData', (newValue) -> changed = false for key, value of newValue oldParamValue = $scope.submitterParams[key] if value && value.length > 0 $scope.submitterParams[key] = value else $scope.submitterParams[key] = null changed |= oldParamValue != $scope.submitterParams[key] updateSubmitterParams() $scope.reload() if changed return , true $scope.courseSearch = (nameQuery) -> CoursesResource.query({ name: nameQuery, page: 1, page_size: 100 }).$promise.then (data) -> data.courses $scope.projectSearch = (nameQuery, course) -> CourseProjectsResource.query({ course_id: course.id, page: 1, page_size: 100, name: nameQuery }).$promise.then (data) -> data.projects submissionFactory = (data) -> return new Submission data, deletedSubmissionCallback addSubmissionsCallback = (newSubmissions) -> submissions = _.filter newSubmissions, (s) -> s.id not in deletedSubmissionIds args = [0, $scope.submissions.length].concat submissions $scope.submissions.splice.apply $scope.submissions, args $scope.submissionsPagination = new Pagination ProjectSubmissionsResource, 'submissions', $scope.submissionParams, submissionFactory, defaultPageSize $scope.reload = -> return if $scope.loadingSubmissions $scope.loadingSubmissions = true $scope.submissionsPagination.reload().then (submissions) -> $scope.loadingSubmissions = false addSubmissionsCallback submissions loadSubmissionsPage = (page) -> $scope.loadingSubmissions = true $scope.submissionsPagination.page(page).then (submissions) -> $scope.loadingSubmissions = false $scope.currentPage = page addSubmissionsCallback submissions $scope.currentPage = 1 $scope.selectProject = (project) -> if project $scope.currentPage = 1 $scope.submissionParams.project_id = project.id $scope.reload() else $scope.submissionParams.project_id = null $scope.backDisabled = -> $scope.currentPage is 1 $scope.nextDisabled = -> $scope.currentPage >= $scope.submissionsPagination.totalPages $scope.next = -> if not $scope.nextDisabled() loadSubmissionsPage($scope.currentPage + 1) $scope.back = -> if not $scope.backDisabled() loadSubmissionsPage($scope.currentPage - 1)
[ { "context": "# parsing C# code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 55, "score": 0.9998639225959778, "start": 41, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": "# code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ", "end": 69, "score": 0.8218182921409607, "start": 61, "tag": "USERNAME", "value": "Outsider" } ]
src/parser/csharp-parser.coffee
outsideris/popularconvention
421
# parsing C# code # # Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> helpers = require '../helpers' _ = require 'underscore' javaParser = module.exports = lang: 'csharp' parse: (line, convention, commitUrl) -> convention = this.indent line, convention, commitUrl convention = this.blockstatement line, convention, commitUrl convention = this.constant line, convention, commitUrl convention = this.conditionstatement line, convention, commitUrl convention = this.argumentdef line, convention, commitUrl convention = this.linelength line, convention, commitUrl indent: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.indent = title: "Space vs. Tab" column: [ { key: "tab", display: "Tab", code: """ public string GetSomething() { // use tab for indentation return something; } """ } { key: "space", display: "Space", code: """ public string GetSomething() { return something; } """ } ] tab: 0 space: 0 commits: [] ) unless convention.indent tab = /^\t+.*/ space = /^\s+.*/ convention.indent.tab = convention.indent.tab + 1 if tab.test line convention.indent.space = convention.indent.space + 1 if space.test line convention.indent.commits.push commitUrl if tab.test(line) or space.test(line) convention.indent.commits = _.uniq convention.indent.commits convention blockstatement: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.blockstatement = title: "How to write block statements" column: [ { key: "onespace", display: "Curlybrace with one space", code: """ if (height < MIN_HEIGHT) { //.. } while (isTrue) { //.. } switch (foo) { //.. } """ } { key: "nospace", display: "Curlybrace with no space", code: """ if (height < MIN_HEIGHT){ //.. } while (isTrue){ //.. } switch (foo){ //.. } """ } { key: "newline", display: "Curlybrace at new line", code: """ if (height < MIN_HEIGHT) { //.. } while (isTrue) { //.. } switch (foo) { //.. } """ } ] onespace: 0 nospace: 0 newline: 0 commits: [] ) unless convention.blockstatement onespace = /((if|while|switch|try).*\s+{)|(}\s+(else|catch|finally).*\s+{)/ nospace = /((if|while|switch).*\){)|(try|else|finally){|(}\s*(else|catch|finally).*\){)/ newline = /((if|while|switch).*\)\s*$)|((if|while|switch).*\)\s*\/[\/\*])|(try|else|finally)\s*\/[\/\*]|(^\s*(else|catch|finally))/ convention.blockstatement.onespace = convention.blockstatement.onespace + 1 if onespace.test line convention.blockstatement.nospace = convention.blockstatement.nospace + 1 if nospace.test line convention.blockstatement.newline = convention.blockstatement.newline + 1 if newline.test line convention.blockstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) or newline.test(line) convention.blockstatement.commits = _.uniq convention.blockstatement.commits convention constant: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.constant = title: "Constant name" column: [ { key: "pascal", display: "Constant is Pascal cased", code: """ const string FooBar = "baz"; """ } { key: "allcaps", display: "Constant name is all caps with underscore(_)", code: """ const string FOO_BAR = "baz"; """ } { key: "notallcaps", display: "Constant name is neither all caps and pascal cased", code: """ const string foo_bar = "baz"; const string fooBar = "baz"; """ } ] pascal: 0 allcaps: 0 notallcaps: 0 commits: [] ) unless convention.constant pascal = /const\s+\w+\s+([A-Z][a-z0-9]+)+\s*=/ allcaps = /const\s+\w+\s+([A-Z0-9_]+)+\s*=/ notallcaps = /const\s+\w+\s+([a-z][A-Za-z0-9_]*)+\s*=/ convention.constant.pascal = convention.constant.pascal + 1 if pascal.test line convention.constant.allcaps = convention.constant.allcaps + 1 if allcaps.test line convention.constant.notallcaps = convention.constant.notallcaps + 1 if notallcaps.test line convention.constant.commits.push commitUrl if pascal.test(line) or allcaps.test(line) or notallcaps.test(line) convention.constant.commits = _.uniq convention.constant.commits convention conditionstatement: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.conditionstatement = title: "How to write conditional statement" column: [ { key: "onespace", display: "Condition with one space", code: """ if (true) { //... } while (true) { //... } switch (v) { //... } """ } { key: "nospace", display: "Condition with no space", code: """ if(true) { //... } while(true) { //... } switch(v) { //... } """ } ] onespace: 0 nospace: 0 commits: [] ) unless convention.conditionstatement onespace = /(if|while|switch)\s+\(/ nospace = /(if|while|switch)\(/ convention.conditionstatement.onespace = convention.conditionstatement.onespace + 1 if onespace.test line convention.conditionstatement.nospace = convention.conditionstatement.nospace + 1 if nospace.test line convention.conditionstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) convention.conditionstatement.commits = _.uniq convention.conditionstatement.commits convention argumentdef: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.argumentdef = title: "Arguments definition with one space vs. no space" column: [ { key: "onespace", display: "One space", code: """ public void SetName( String name ) { // ... } if( isTrue ) {} while( isTrue ) {} """ } { key: "nospace", display: "No space", code: """ public void SetName(String name) { // ... } if(isTrue) {} while(isTrue) {} """ } ] onespace: 0 nospace: 0 commits: [] ) unless convention.argumentdef onespace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\s+/ nospace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\S+/ convention.argumentdef.onespace = convention.argumentdef.onespace + 1 if onespace.test line convention.argumentdef.nospace = convention.argumentdef.nospace + 1 if nospace.test line convention.argumentdef.commits.push commitUrl if onespace.test(line) or nospace.test(line) convention.argumentdef.commits = _.uniq convention.argumentdef.commits convention linelength: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.linelength = title: "Line length is over 80 characters?" column: [ { key: "char80", display: "Line length is within 80 characters.", code: "/* width is within 80 characters */" } { key: "char120", display: "Line length is within 120 characters", code: "/* width is within 120 characters */" } { key: "char150", display: "Line length is within 150 characters", code: "/* width is within 150 characters */" } ] char80: 0 char120: 0 char150: 0 commits: [] ) unless convention.linelength width = line.length tabcount = line.split('\t').length - 1 # assume tab size is 4 space width += tabcount * 3 if width < 80 convention.linelength.char80 = convention.linelength.char80 + 1 else if width < 120 convention.linelength.char120 = convention.linelength.char120 + 1 else convention.linelength.char150 = convention.linelength.char150 + 1 convention.linelength.commits.push commitUrl convention.linelength.commits = _.uniq convention.linelength.commits convention
84935
# parsing C# code # # Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> helpers = require '../helpers' _ = require 'underscore' javaParser = module.exports = lang: 'csharp' parse: (line, convention, commitUrl) -> convention = this.indent line, convention, commitUrl convention = this.blockstatement line, convention, commitUrl convention = this.constant line, convention, commitUrl convention = this.conditionstatement line, convention, commitUrl convention = this.argumentdef line, convention, commitUrl convention = this.linelength line, convention, commitUrl indent: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.indent = title: "Space vs. Tab" column: [ { key: "tab", display: "Tab", code: """ public string GetSomething() { // use tab for indentation return something; } """ } { key: "space", display: "Space", code: """ public string GetSomething() { return something; } """ } ] tab: 0 space: 0 commits: [] ) unless convention.indent tab = /^\t+.*/ space = /^\s+.*/ convention.indent.tab = convention.indent.tab + 1 if tab.test line convention.indent.space = convention.indent.space + 1 if space.test line convention.indent.commits.push commitUrl if tab.test(line) or space.test(line) convention.indent.commits = _.uniq convention.indent.commits convention blockstatement: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.blockstatement = title: "How to write block statements" column: [ { key: "onespace", display: "Curlybrace with one space", code: """ if (height < MIN_HEIGHT) { //.. } while (isTrue) { //.. } switch (foo) { //.. } """ } { key: "nospace", display: "Curlybrace with no space", code: """ if (height < MIN_HEIGHT){ //.. } while (isTrue){ //.. } switch (foo){ //.. } """ } { key: "newline", display: "Curlybrace at new line", code: """ if (height < MIN_HEIGHT) { //.. } while (isTrue) { //.. } switch (foo) { //.. } """ } ] onespace: 0 nospace: 0 newline: 0 commits: [] ) unless convention.blockstatement onespace = /((if|while|switch|try).*\s+{)|(}\s+(else|catch|finally).*\s+{)/ nospace = /((if|while|switch).*\){)|(try|else|finally){|(}\s*(else|catch|finally).*\){)/ newline = /((if|while|switch).*\)\s*$)|((if|while|switch).*\)\s*\/[\/\*])|(try|else|finally)\s*\/[\/\*]|(^\s*(else|catch|finally))/ convention.blockstatement.onespace = convention.blockstatement.onespace + 1 if onespace.test line convention.blockstatement.nospace = convention.blockstatement.nospace + 1 if nospace.test line convention.blockstatement.newline = convention.blockstatement.newline + 1 if newline.test line convention.blockstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) or newline.test(line) convention.blockstatement.commits = _.uniq convention.blockstatement.commits convention constant: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.constant = title: "Constant name" column: [ { key: "pascal", display: "Constant is Pascal cased", code: """ const string FooBar = "baz"; """ } { key: "allcaps", display: "Constant name is all caps with underscore(_)", code: """ const string FOO_BAR = "baz"; """ } { key: "notallcaps", display: "Constant name is neither all caps and pascal cased", code: """ const string foo_bar = "baz"; const string fooBar = "baz"; """ } ] pascal: 0 allcaps: 0 notallcaps: 0 commits: [] ) unless convention.constant pascal = /const\s+\w+\s+([A-Z][a-z0-9]+)+\s*=/ allcaps = /const\s+\w+\s+([A-Z0-9_]+)+\s*=/ notallcaps = /const\s+\w+\s+([a-z][A-Za-z0-9_]*)+\s*=/ convention.constant.pascal = convention.constant.pascal + 1 if pascal.test line convention.constant.allcaps = convention.constant.allcaps + 1 if allcaps.test line convention.constant.notallcaps = convention.constant.notallcaps + 1 if notallcaps.test line convention.constant.commits.push commitUrl if pascal.test(line) or allcaps.test(line) or notallcaps.test(line) convention.constant.commits = _.uniq convention.constant.commits convention conditionstatement: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.conditionstatement = title: "How to write conditional statement" column: [ { key: "onespace", display: "Condition with one space", code: """ if (true) { //... } while (true) { //... } switch (v) { //... } """ } { key: "nospace", display: "Condition with no space", code: """ if(true) { //... } while(true) { //... } switch(v) { //... } """ } ] onespace: 0 nospace: 0 commits: [] ) unless convention.conditionstatement onespace = /(if|while|switch)\s+\(/ nospace = /(if|while|switch)\(/ convention.conditionstatement.onespace = convention.conditionstatement.onespace + 1 if onespace.test line convention.conditionstatement.nospace = convention.conditionstatement.nospace + 1 if nospace.test line convention.conditionstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) convention.conditionstatement.commits = _.uniq convention.conditionstatement.commits convention argumentdef: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.argumentdef = title: "Arguments definition with one space vs. no space" column: [ { key: "onespace", display: "One space", code: """ public void SetName( String name ) { // ... } if( isTrue ) {} while( isTrue ) {} """ } { key: "nospace", display: "No space", code: """ public void SetName(String name) { // ... } if(isTrue) {} while(isTrue) {} """ } ] onespace: 0 nospace: 0 commits: [] ) unless convention.argumentdef onespace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\s+/ nospace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\S+/ convention.argumentdef.onespace = convention.argumentdef.onespace + 1 if onespace.test line convention.argumentdef.nospace = convention.argumentdef.nospace + 1 if nospace.test line convention.argumentdef.commits.push commitUrl if onespace.test(line) or nospace.test(line) convention.argumentdef.commits = _.uniq convention.argumentdef.commits convention linelength: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.linelength = title: "Line length is over 80 characters?" column: [ { key: "char80", display: "Line length is within 80 characters.", code: "/* width is within 80 characters */" } { key: "char120", display: "Line length is within 120 characters", code: "/* width is within 120 characters */" } { key: "char150", display: "Line length is within 150 characters", code: "/* width is within 150 characters */" } ] char80: 0 char120: 0 char150: 0 commits: [] ) unless convention.linelength width = line.length tabcount = line.split('\t').length - 1 # assume tab size is 4 space width += tabcount * 3 if width < 80 convention.linelength.char80 = convention.linelength.char80 + 1 else if width < 120 convention.linelength.char120 = convention.linelength.char120 + 1 else convention.linelength.char150 = convention.linelength.char150 + 1 convention.linelength.commits.push commitUrl convention.linelength.commits = _.uniq convention.linelength.commits convention
true
# parsing C# code # # Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> helpers = require '../helpers' _ = require 'underscore' javaParser = module.exports = lang: 'csharp' parse: (line, convention, commitUrl) -> convention = this.indent line, convention, commitUrl convention = this.blockstatement line, convention, commitUrl convention = this.constant line, convention, commitUrl convention = this.conditionstatement line, convention, commitUrl convention = this.argumentdef line, convention, commitUrl convention = this.linelength line, convention, commitUrl indent: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.indent = title: "Space vs. Tab" column: [ { key: "tab", display: "Tab", code: """ public string GetSomething() { // use tab for indentation return something; } """ } { key: "space", display: "Space", code: """ public string GetSomething() { return something; } """ } ] tab: 0 space: 0 commits: [] ) unless convention.indent tab = /^\t+.*/ space = /^\s+.*/ convention.indent.tab = convention.indent.tab + 1 if tab.test line convention.indent.space = convention.indent.space + 1 if space.test line convention.indent.commits.push commitUrl if tab.test(line) or space.test(line) convention.indent.commits = _.uniq convention.indent.commits convention blockstatement: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.blockstatement = title: "How to write block statements" column: [ { key: "onespace", display: "Curlybrace with one space", code: """ if (height < MIN_HEIGHT) { //.. } while (isTrue) { //.. } switch (foo) { //.. } """ } { key: "nospace", display: "Curlybrace with no space", code: """ if (height < MIN_HEIGHT){ //.. } while (isTrue){ //.. } switch (foo){ //.. } """ } { key: "newline", display: "Curlybrace at new line", code: """ if (height < MIN_HEIGHT) { //.. } while (isTrue) { //.. } switch (foo) { //.. } """ } ] onespace: 0 nospace: 0 newline: 0 commits: [] ) unless convention.blockstatement onespace = /((if|while|switch|try).*\s+{)|(}\s+(else|catch|finally).*\s+{)/ nospace = /((if|while|switch).*\){)|(try|else|finally){|(}\s*(else|catch|finally).*\){)/ newline = /((if|while|switch).*\)\s*$)|((if|while|switch).*\)\s*\/[\/\*])|(try|else|finally)\s*\/[\/\*]|(^\s*(else|catch|finally))/ convention.blockstatement.onespace = convention.blockstatement.onespace + 1 if onespace.test line convention.blockstatement.nospace = convention.blockstatement.nospace + 1 if nospace.test line convention.blockstatement.newline = convention.blockstatement.newline + 1 if newline.test line convention.blockstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) or newline.test(line) convention.blockstatement.commits = _.uniq convention.blockstatement.commits convention constant: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.constant = title: "Constant name" column: [ { key: "pascal", display: "Constant is Pascal cased", code: """ const string FooBar = "baz"; """ } { key: "allcaps", display: "Constant name is all caps with underscore(_)", code: """ const string FOO_BAR = "baz"; """ } { key: "notallcaps", display: "Constant name is neither all caps and pascal cased", code: """ const string foo_bar = "baz"; const string fooBar = "baz"; """ } ] pascal: 0 allcaps: 0 notallcaps: 0 commits: [] ) unless convention.constant pascal = /const\s+\w+\s+([A-Z][a-z0-9]+)+\s*=/ allcaps = /const\s+\w+\s+([A-Z0-9_]+)+\s*=/ notallcaps = /const\s+\w+\s+([a-z][A-Za-z0-9_]*)+\s*=/ convention.constant.pascal = convention.constant.pascal + 1 if pascal.test line convention.constant.allcaps = convention.constant.allcaps + 1 if allcaps.test line convention.constant.notallcaps = convention.constant.notallcaps + 1 if notallcaps.test line convention.constant.commits.push commitUrl if pascal.test(line) or allcaps.test(line) or notallcaps.test(line) convention.constant.commits = _.uniq convention.constant.commits convention conditionstatement: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.conditionstatement = title: "How to write conditional statement" column: [ { key: "onespace", display: "Condition with one space", code: """ if (true) { //... } while (true) { //... } switch (v) { //... } """ } { key: "nospace", display: "Condition with no space", code: """ if(true) { //... } while(true) { //... } switch(v) { //... } """ } ] onespace: 0 nospace: 0 commits: [] ) unless convention.conditionstatement onespace = /(if|while|switch)\s+\(/ nospace = /(if|while|switch)\(/ convention.conditionstatement.onespace = convention.conditionstatement.onespace + 1 if onespace.test line convention.conditionstatement.nospace = convention.conditionstatement.nospace + 1 if nospace.test line convention.conditionstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) convention.conditionstatement.commits = _.uniq convention.conditionstatement.commits convention argumentdef: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.argumentdef = title: "Arguments definition with one space vs. no space" column: [ { key: "onespace", display: "One space", code: """ public void SetName( String name ) { // ... } if( isTrue ) {} while( isTrue ) {} """ } { key: "nospace", display: "No space", code: """ public void SetName(String name) { // ... } if(isTrue) {} while(isTrue) {} """ } ] onespace: 0 nospace: 0 commits: [] ) unless convention.argumentdef onespace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\s+/ nospace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\S+/ convention.argumentdef.onespace = convention.argumentdef.onespace + 1 if onespace.test line convention.argumentdef.nospace = convention.argumentdef.nospace + 1 if nospace.test line convention.argumentdef.commits.push commitUrl if onespace.test(line) or nospace.test(line) convention.argumentdef.commits = _.uniq convention.argumentdef.commits convention linelength: (line, convention, commitUrl) -> convention = {lang: this.lang} unless convention (convention.linelength = title: "Line length is over 80 characters?" column: [ { key: "char80", display: "Line length is within 80 characters.", code: "/* width is within 80 characters */" } { key: "char120", display: "Line length is within 120 characters", code: "/* width is within 120 characters */" } { key: "char150", display: "Line length is within 150 characters", code: "/* width is within 150 characters */" } ] char80: 0 char120: 0 char150: 0 commits: [] ) unless convention.linelength width = line.length tabcount = line.split('\t').length - 1 # assume tab size is 4 space width += tabcount * 3 if width < 80 convention.linelength.char80 = convention.linelength.char80 + 1 else if width < 120 convention.linelength.char120 = convention.linelength.char120 + 1 else convention.linelength.char150 = convention.linelength.char150 + 1 convention.linelength.commits.push commitUrl convention.linelength.commits = _.uniq convention.linelength.commits convention
[ { "context": "GGING == \"true\"\n npmUsername: process.env.NPM_USERNAME\n npmPassword: process.env.NPM_PASSWORD\n ", "end": 277, "score": 0.9011438488960266, "start": 265, "tag": "USERNAME", "value": "NPM_USERNAME" }, { "context": " process.env.NPM_USERNAME\n npmPassword: process.env.NPM_PASSWORD\n npmEmail: process.env.NPM_EMAIL\n ", "end": 324, "score": 0.9802694916725159, "start": 300, "tag": "PASSWORD", "value": "process.env.NPM_PASSWORD" }, { "context": " new Error('Missing required environment variable: NPM_USERNAME') if _.isEmpty @serverOptions.npmUsername\n @pa", "end": 686, "score": 0.8257524371147156, "start": 674, "tag": "USERNAME", "value": "NPM_USERNAME" } ]
command.coffee
octoblu/connector-detail-service
0
_ = require 'lodash' Server = require './src/server' class Command constructor: -> @serverOptions = port: process.env.PORT || 80 disableLogging: process.env.DISABLE_LOGGING == "true" npmUsername: process.env.NPM_USERNAME npmPassword: process.env.NPM_PASSWORD npmEmail: process.env.NPM_EMAIL githubToken: process.env.GITHUB_TOKEN panic: (error) => console.error error.stack process.exit 1 run: => @panic new Error('Missing required environment variable: GITHUB_TOKEN') if _.isEmpty @serverOptions.githubToken @panic new Error('Missing required environment variable: NPM_USERNAME') if _.isEmpty @serverOptions.npmUsername @panic new Error('Missing required environment variable: NPM_PASSWORD') if _.isEmpty @serverOptions.npmPassword @panic new Error('Missing required environment variable: NPM_EMAIL') if _.isEmpty @serverOptions.npmEmail server = new Server @serverOptions server.run (error) => return @panic error if error? {address,port} = server.address() console.log "Server listening on #{address}:#{port}" command = new Command() command.run()
219132
_ = require 'lodash' Server = require './src/server' class Command constructor: -> @serverOptions = port: process.env.PORT || 80 disableLogging: process.env.DISABLE_LOGGING == "true" npmUsername: process.env.NPM_USERNAME npmPassword: <PASSWORD> npmEmail: process.env.NPM_EMAIL githubToken: process.env.GITHUB_TOKEN panic: (error) => console.error error.stack process.exit 1 run: => @panic new Error('Missing required environment variable: GITHUB_TOKEN') if _.isEmpty @serverOptions.githubToken @panic new Error('Missing required environment variable: NPM_USERNAME') if _.isEmpty @serverOptions.npmUsername @panic new Error('Missing required environment variable: NPM_PASSWORD') if _.isEmpty @serverOptions.npmPassword @panic new Error('Missing required environment variable: NPM_EMAIL') if _.isEmpty @serverOptions.npmEmail server = new Server @serverOptions server.run (error) => return @panic error if error? {address,port} = server.address() console.log "Server listening on #{address}:#{port}" command = new Command() command.run()
true
_ = require 'lodash' Server = require './src/server' class Command constructor: -> @serverOptions = port: process.env.PORT || 80 disableLogging: process.env.DISABLE_LOGGING == "true" npmUsername: process.env.NPM_USERNAME npmPassword: PI:PASSWORD:<PASSWORD>END_PI npmEmail: process.env.NPM_EMAIL githubToken: process.env.GITHUB_TOKEN panic: (error) => console.error error.stack process.exit 1 run: => @panic new Error('Missing required environment variable: GITHUB_TOKEN') if _.isEmpty @serverOptions.githubToken @panic new Error('Missing required environment variable: NPM_USERNAME') if _.isEmpty @serverOptions.npmUsername @panic new Error('Missing required environment variable: NPM_PASSWORD') if _.isEmpty @serverOptions.npmPassword @panic new Error('Missing required environment variable: NPM_EMAIL') if _.isEmpty @serverOptions.npmEmail server = new Server @serverOptions server.run (error) => return @panic error if error? {address,port} = server.address() console.log "Server listening on #{address}:#{port}" command = new Command() command.run()
[ { "context": "calvin:\n id: 'calvin'\n\n startDate: '2016-09-28'\n endDate: '2016-0", "end": 25, "score": 0.6642548441886902, "start": 22, "tag": "USERNAME", "value": "cal" }, { "context": "calvin:\n id: 'calvin'\n\n startDate: '2016-09-28'\n endDate: '2016-09-2", "end": 28, "score": 0.5911338925361633, "start": 25, "tag": "NAME", "value": "vin" } ]
test/fixtures/non-recurring-today-we-are-in-it.cson
octoblu/groundhog-day-service
0
calvin: id: 'calvin' startDate: '2016-09-28' endDate: '2016-09-28' duration: length: 2 units: 'hours' schedules: [ startTimes: ['14:00:00'] ]
82517
calvin: id: 'cal<NAME>' startDate: '2016-09-28' endDate: '2016-09-28' duration: length: 2 units: 'hours' schedules: [ startTimes: ['14:00:00'] ]
true
calvin: id: 'calPI:NAME:<NAME>END_PI' startDate: '2016-09-28' endDate: '2016-09-28' duration: length: 2 units: 'hours' schedules: [ startTimes: ['14:00:00'] ]
[ { "context": "Prevent definitions of unused prop types\n# @author Evgueni Naverniouk\n###\n'use strict'\n\n# As for exceptions for props.c", "end": 90, "score": 0.9998604655265808, "start": 72, "tag": "NAME", "value": "Evgueni Naverniouk" }, { "context": "lassName (and alike) look at\n# https://github.com/yannickcr/eslint-plugin-react/issues/7\n\nComponents = requir", "end": 217, "score": 0.9996898174285889, "start": 208, "tag": "USERNAME", "value": "yannickcr" } ]
src/rules/no-unused-prop-types.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Prevent definitions of unused prop types # @author Evgueni Naverniouk ### 'use strict' # As for exceptions for props.children or props.className (and alike) look at # https://github.com/yannickcr/eslint-plugin-react/issues/7 Components = require '../util/react/Components' astUtil = require '../util/react/ast' versionUtil = require 'eslint-plugin-react/lib/util/version' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Constants # ------------------------------------------------------------------------------ DIRECT_PROPS_REGEX = /^props\s*(\.|\[)/ DIRECT_NEXT_PROPS_REGEX = /^nextProps\s*(\.|\[)/ DIRECT_PREV_PROPS_REGEX = /^prevProps\s*(\.|\[)/ LIFE_CYCLE_METHODS = [ 'componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'componentDidUpdate' ] ASYNC_SAFE_LIFE_CYCLE_METHODS = [ 'getDerivedStateFromProps' 'getSnapshotBeforeUpdate' 'UNSAFE_componentWillReceiveProps' 'UNSAFE_componentWillUpdate' ] # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Prevent definitions of unused prop types' category: 'Best Practices' recommended: no url: docsUrl 'no-unused-prop-types' schema: [ type: 'object' properties: customValidators: type: 'array' items: type: 'string' skipShapeProps: type: 'boolean' additionalProperties: no ] create: Components.detect (context, components, utils) -> sourceCode = context.getSourceCode() checkAsyncSafeLifeCycles = versionUtil.testReactVersion context, '16.3.0' defaults = skipShapeProps: yes, customValidators: [] configuration = {...defaults, ...(context.options[0] or {})} UNUSED_MESSAGE = "'{{name}}' PropType is defined but prop is never used" # ###* # Check if we are in a lifecycle method # @return {boolean} true if we are in a class constructor, false if not ### inLifeCycleMethod = -> scope = context.getScope() while scope if scope.block?.parent?.key {name} = scope.block.parent.key return yes if LIFE_CYCLE_METHODS.indexOf(name) >= 0 return yes if ( checkAsyncSafeLifeCycles and ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(name) >= 0 ) scope = scope.upper no ###* # Check if the current node is in a setState updater method # @return {boolean} true if we are in a setState updater, false if not ### inSetStateUpdater = -> scope = context.getScope() while scope return yes if ( scope.block?.parent?.type is 'CallExpression' and scope.block.parent.callee.property?.name is 'setState' and # Make sure we are in the updater not the callback scope.block.parent.arguments[0].start is scope.block.start ) scope = scope.upper no isPropArgumentInSetStateUpdater = (node) -> scope = context.getScope() while scope return ( scope.block.parent.arguments[0].params[1].name is node.object.name ) if ( scope.block?.parent and scope.block.parent.type is 'CallExpression' and scope.block.parent.callee.property and scope.block.parent.callee.property.name is 'setState' and # Make sure we are in the updater not the callback scope.block.parent.arguments[0].start is scope.block.start and scope.block.parent.arguments[0].params and scope.block.parent.arguments[0].params.length > 1 ) scope = scope.upper no ###* # Checks if we are using a prop # @param {ASTNode} node The AST node being checked. # @returns {Boolean} True if we are using a prop, false if not. ### isPropTypesUsage = (node) -> isClassUsage = (utils.getParentES6Component() or utils.getParentES5Component()) and ((node.object.type is 'ThisExpression' and node.property.name is 'props') or isPropArgumentInSetStateUpdater node) isStatelessFunctionUsage = node.object.name is 'props' isClassUsage or isStatelessFunctionUsage or inLifeCycleMethod() ###* # Checks if the component must be validated # @param {Object} component The component to process # @returns {Boolean} True if the component must be validated, false if not. ### mustBeValidated = (component) -> Boolean component and not component.ignoreUnusedPropTypesValidation ###* # Returns true if the given node is a React Component lifecycle method # @param {ASTNode} node The AST node being checked. # @return {Boolean} True if the node is a lifecycle method ### isNodeALifeCycleMethod = (node) -> nodeKeyName = node.key?.name return yes if node.kind is 'constructor' return yes if LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0 return yes if ( checkAsyncSafeLifeCycles and ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0 ) no ###* # Returns true if the given node is inside a React Component lifecycle # method. # @param {ASTNode} node The AST node being checked. # @return {Boolean} True if the node is inside a lifecycle method ### isInLifeCycleMethod = (node) -> return yes if ( node.type in ['MethodDefinition', 'Property'] and isNodeALifeCycleMethod node ) return isInLifeCycleMethod node.parent if node.parent no ###* # Checks if a prop init name matches common naming patterns # @param {ASTNode} node The AST node being checked. # @returns {Boolean} True if the prop name matches ### isPropAttributeName = (node) -> (node.init ? node.right).name in ['props', 'nextProps', 'prevProps'] ###* # Checks if a prop is used # @param {ASTNode} node The AST node being checked. # @param {Object} prop Declared prop object # @returns {Boolean} True if the prop is used, false if not. ### isPropUsed = (node, prop) -> usedPropTypes = node.usedPropTypes or [] i = 0 l = usedPropTypes.length while i < l usedProp = usedPropTypes[i] return yes if ( prop.type is 'shape' or prop.name is '__ANY_KEY__' or usedProp.name is prop.name ) i++ no ###* # Checks if the prop has spread operator. # @param {ASTNode} node The AST node being marked. # @returns {Boolean} True if the prop has spread operator, false if not. ### hasSpreadOperator = (node) -> tokens = sourceCode.getTokens node tokens.length and tokens[0].value is '...' ###* # Removes quotes from around an identifier. # @param {string} the identifier to strip ### stripQuotes = (string) -> string.replace /^'|'$/g, '' ###* # Retrieve the name of a key node # @param {ASTNode} node The AST node with the key. # @return {string} the name of the key ### getKeyValue = (node) -> if node.type is 'ObjectTypeProperty' tokens = context.getFirstTokens node, 2 return ( if tokens[0].value in ['+', '-'] tokens[1].value else stripQuotes tokens[0].value ) key = node.key or node.argument if key.type is 'Identifier' then key.name else key.value ###* # Check if we are in a class constructor # @return {boolean} true if we are in a class constructor, false if not ### inConstructor = -> scope = context.getScope() while scope return yes if ( scope.block?.parent and scope.block.parent.kind is 'constructor' ) scope = scope.upper no ###* # Retrieve the name of a property node # @param {ASTNode} node The AST node with the property. # @return {string} the name of the property or undefined if not found ### getPropertyName = (node) -> isDirectProp = DIRECT_PROPS_REGEX.test sourceCode.getText node isDirectNextProp = DIRECT_NEXT_PROPS_REGEX.test sourceCode.getText node isDirectPrevProp = DIRECT_PREV_PROPS_REGEX.test sourceCode.getText node isDirectSetStateProp = isPropArgumentInSetStateUpdater node isInClassComponent = utils.getParentES6Component() or utils.getParentES5Component() isNotInConstructor = not inConstructor node isNotInLifeCycleMethod = not inLifeCycleMethod() isNotInSetStateUpdater = not inSetStateUpdater() return undefined if ( (isDirectProp or isDirectNextProp or isDirectPrevProp or isDirectSetStateProp) and isInClassComponent and isNotInConstructor and isNotInLifeCycleMethod and isNotInSetStateUpdater ) if ( not isDirectProp and not isDirectNextProp and not isDirectPrevProp and not isDirectSetStateProp ) node = node.parent {property} = node if property switch property.type when 'Identifier' return '__COMPUTED_PROP__' if node.computed return property.name when 'MemberExpression' return undefined when 'Literal' # Accept computed properties that are literal strings return property.value if typeof property.value is 'string' return '__COMPUTED_PROP__' if node.computed else return '__COMPUTED_PROP__' if node.computed undefined ###* # Mark a prop type as used # @param {ASTNode} node The AST node being marked. ### markPropTypesAsUsed = (node, parentNames) -> parentNames or= [] switch node.type when 'MemberExpression' name = getPropertyName node if name allNames = parentNames.concat name if node.parent.type is 'MemberExpression' markPropTypesAsUsed node.parent, allNames # Do not mark computed props as used. type = unless name is '__COMPUTED_PROP__' then 'direct' else null else left = node.parent.id ? node.parent.left if left?.properties?.length and getKeyValue left.properties[0] type = 'destructuring' {properties} = left when 'ArrowFunctionExpression', 'FunctionDeclaration', 'FunctionExpression' break unless node.params.length type = 'destructuring' {properties} = node.params[0] {properties} = node.params[1] ? {} if inSetStateUpdater() when 'VariableDeclarator', 'AssignmentExpression' left = node.id ? node.left # let {props: {firstname}} = this # let {firstname} = props for property in left.properties thisDestructuring = property.key and ((property.key.name is 'props' or property.key.value is 'props') and property.value.type is 'ObjectPattern') genericDestructuring = isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) if thisDestructuring {properties} = property.value else if genericDestructuring {properties} = left else continue type = 'destructuring' else throw new Error( "#{node.type} ASTNodes are not handled by markPropTypesAsUsed" ) component = components.get utils.getParentComponent() usedPropTypes = component?.usedPropTypes or [] ignoreUnusedPropTypesValidation = component?.ignoreUnusedPropTypesValidation or no switch type when 'direct' # Ignore Object methods break if Object::[name] usedPropTypes.push { name allNames } when 'destructuring' for property in properties or [] if hasSpreadOperator(property) or property.computed ignoreUnusedPropTypesValidation = yes propName = getKeyValue property currentNode = node allNames = [] while ( currentNode.property and currentNode.property.name isnt 'props' ) allNames.unshift currentNode.property.name currentNode = currentNode.object allNames.push propName if propName usedPropTypes.push { allNames name: propName } components.set component?.node ? node, { usedPropTypes ignoreUnusedPropTypesValidation } ###* # Used to recursively loop through each declared prop type # @param {Object} component The component to process # @param {Array} props List of props to validate ### reportUnusedPropType = (component, props) -> # Skip props that check instances return if props is yes Object.keys(props or {}).forEach (key) -> prop = props[key] # Skip props that check instances return if prop is yes return if prop.type is 'shape' and configuration.skipShapeProps if prop.node and not isPropUsed component, prop context.report prop.node, UNUSED_MESSAGE, name: prop.fullName if prop.children then reportUnusedPropType component, prop.children ###* # Reports unused proptypes for a given component # @param {Object} component The component to process ### reportUnusedPropTypes = (component) -> reportUnusedPropType component, component.declaredPropTypes ###* # @param {ASTNode} node We expect either an ArrowFunctionExpression, # FunctionDeclaration, or FunctionExpression ### markDestructuredFunctionArgumentsAsUsed = (node) -> destructuring = node.params?[0]?.type is 'ObjectPattern' if destructuring and components.get node then markPropTypesAsUsed node handleSetStateUpdater = (node) -> return unless node.params?.length >= 2 and inSetStateUpdater() markPropTypesAsUsed node ###* # Handle both stateless functions and setState updater functions. # @param {ASTNode} node We expect either an ArrowFunctionExpression, # FunctionDeclaration, or FunctionExpression ### handleFunctionLikeExpressions = (node) -> handleSetStateUpdater node markDestructuredFunctionArgumentsAsUsed node handleCustomValidators = (component) -> propTypes = component.declaredPropTypes return unless propTypes Object.keys(propTypes).forEach (key) -> {node} = propTypes[key] if astUtil.isFunctionLikeExpression node then markPropTypesAsUsed node # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- VariableDeclarator: (node) -> destructuring = node.init and node.id and node.id.type is 'ObjectPattern' # let {props: {firstname}} = this thisDestructuring = destructuring and node.init.type is 'ThisExpression' # let {firstname} = props statelessDestructuring = destructuring and isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) return if not thisDestructuring and not statelessDestructuring markPropTypesAsUsed node AssignmentExpression: (node) -> destructuring = node.left.type is 'ObjectPattern' # let {props: {firstname}} = this thisDestructuring = destructuring and node.right.type is 'ThisExpression' # let {firstname} = props statelessDestructuring = destructuring and isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) return unless thisDestructuring or statelessDestructuring markPropTypesAsUsed node FunctionDeclaration: handleFunctionLikeExpressions ArrowFunctionExpression: handleFunctionLikeExpressions FunctionExpression: handleFunctionLikeExpressions MemberExpression: (node) -> markPropTypesAsUsed node if isPropTypesUsage node ObjectPattern: (node) -> # If the object pattern is a destructured props object in a lifecycle # method -- mark it for used props. if isNodeALifeCycleMethod node.parent.parent node.properties.forEach (property, i) -> if i is 0 then markPropTypesAsUsed node.parent 'Program:exit': -> list = components.list() # Report undeclared proptypes for all classes for own _, component of list when mustBeValidated component handleCustomValidators component reportUnusedPropTypes component
46681
###* # @fileoverview Prevent definitions of unused prop types # @author <NAME> ### 'use strict' # As for exceptions for props.children or props.className (and alike) look at # https://github.com/yannickcr/eslint-plugin-react/issues/7 Components = require '../util/react/Components' astUtil = require '../util/react/ast' versionUtil = require 'eslint-plugin-react/lib/util/version' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Constants # ------------------------------------------------------------------------------ DIRECT_PROPS_REGEX = /^props\s*(\.|\[)/ DIRECT_NEXT_PROPS_REGEX = /^nextProps\s*(\.|\[)/ DIRECT_PREV_PROPS_REGEX = /^prevProps\s*(\.|\[)/ LIFE_CYCLE_METHODS = [ 'componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'componentDidUpdate' ] ASYNC_SAFE_LIFE_CYCLE_METHODS = [ 'getDerivedStateFromProps' 'getSnapshotBeforeUpdate' 'UNSAFE_componentWillReceiveProps' 'UNSAFE_componentWillUpdate' ] # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Prevent definitions of unused prop types' category: 'Best Practices' recommended: no url: docsUrl 'no-unused-prop-types' schema: [ type: 'object' properties: customValidators: type: 'array' items: type: 'string' skipShapeProps: type: 'boolean' additionalProperties: no ] create: Components.detect (context, components, utils) -> sourceCode = context.getSourceCode() checkAsyncSafeLifeCycles = versionUtil.testReactVersion context, '16.3.0' defaults = skipShapeProps: yes, customValidators: [] configuration = {...defaults, ...(context.options[0] or {})} UNUSED_MESSAGE = "'{{name}}' PropType is defined but prop is never used" # ###* # Check if we are in a lifecycle method # @return {boolean} true if we are in a class constructor, false if not ### inLifeCycleMethod = -> scope = context.getScope() while scope if scope.block?.parent?.key {name} = scope.block.parent.key return yes if LIFE_CYCLE_METHODS.indexOf(name) >= 0 return yes if ( checkAsyncSafeLifeCycles and ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(name) >= 0 ) scope = scope.upper no ###* # Check if the current node is in a setState updater method # @return {boolean} true if we are in a setState updater, false if not ### inSetStateUpdater = -> scope = context.getScope() while scope return yes if ( scope.block?.parent?.type is 'CallExpression' and scope.block.parent.callee.property?.name is 'setState' and # Make sure we are in the updater not the callback scope.block.parent.arguments[0].start is scope.block.start ) scope = scope.upper no isPropArgumentInSetStateUpdater = (node) -> scope = context.getScope() while scope return ( scope.block.parent.arguments[0].params[1].name is node.object.name ) if ( scope.block?.parent and scope.block.parent.type is 'CallExpression' and scope.block.parent.callee.property and scope.block.parent.callee.property.name is 'setState' and # Make sure we are in the updater not the callback scope.block.parent.arguments[0].start is scope.block.start and scope.block.parent.arguments[0].params and scope.block.parent.arguments[0].params.length > 1 ) scope = scope.upper no ###* # Checks if we are using a prop # @param {ASTNode} node The AST node being checked. # @returns {Boolean} True if we are using a prop, false if not. ### isPropTypesUsage = (node) -> isClassUsage = (utils.getParentES6Component() or utils.getParentES5Component()) and ((node.object.type is 'ThisExpression' and node.property.name is 'props') or isPropArgumentInSetStateUpdater node) isStatelessFunctionUsage = node.object.name is 'props' isClassUsage or isStatelessFunctionUsage or inLifeCycleMethod() ###* # Checks if the component must be validated # @param {Object} component The component to process # @returns {Boolean} True if the component must be validated, false if not. ### mustBeValidated = (component) -> Boolean component and not component.ignoreUnusedPropTypesValidation ###* # Returns true if the given node is a React Component lifecycle method # @param {ASTNode} node The AST node being checked. # @return {Boolean} True if the node is a lifecycle method ### isNodeALifeCycleMethod = (node) -> nodeKeyName = node.key?.name return yes if node.kind is 'constructor' return yes if LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0 return yes if ( checkAsyncSafeLifeCycles and ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0 ) no ###* # Returns true if the given node is inside a React Component lifecycle # method. # @param {ASTNode} node The AST node being checked. # @return {Boolean} True if the node is inside a lifecycle method ### isInLifeCycleMethod = (node) -> return yes if ( node.type in ['MethodDefinition', 'Property'] and isNodeALifeCycleMethod node ) return isInLifeCycleMethod node.parent if node.parent no ###* # Checks if a prop init name matches common naming patterns # @param {ASTNode} node The AST node being checked. # @returns {Boolean} True if the prop name matches ### isPropAttributeName = (node) -> (node.init ? node.right).name in ['props', 'nextProps', 'prevProps'] ###* # Checks if a prop is used # @param {ASTNode} node The AST node being checked. # @param {Object} prop Declared prop object # @returns {Boolean} True if the prop is used, false if not. ### isPropUsed = (node, prop) -> usedPropTypes = node.usedPropTypes or [] i = 0 l = usedPropTypes.length while i < l usedProp = usedPropTypes[i] return yes if ( prop.type is 'shape' or prop.name is '__ANY_KEY__' or usedProp.name is prop.name ) i++ no ###* # Checks if the prop has spread operator. # @param {ASTNode} node The AST node being marked. # @returns {Boolean} True if the prop has spread operator, false if not. ### hasSpreadOperator = (node) -> tokens = sourceCode.getTokens node tokens.length and tokens[0].value is '...' ###* # Removes quotes from around an identifier. # @param {string} the identifier to strip ### stripQuotes = (string) -> string.replace /^'|'$/g, '' ###* # Retrieve the name of a key node # @param {ASTNode} node The AST node with the key. # @return {string} the name of the key ### getKeyValue = (node) -> if node.type is 'ObjectTypeProperty' tokens = context.getFirstTokens node, 2 return ( if tokens[0].value in ['+', '-'] tokens[1].value else stripQuotes tokens[0].value ) key = node.key or node.argument if key.type is 'Identifier' then key.name else key.value ###* # Check if we are in a class constructor # @return {boolean} true if we are in a class constructor, false if not ### inConstructor = -> scope = context.getScope() while scope return yes if ( scope.block?.parent and scope.block.parent.kind is 'constructor' ) scope = scope.upper no ###* # Retrieve the name of a property node # @param {ASTNode} node The AST node with the property. # @return {string} the name of the property or undefined if not found ### getPropertyName = (node) -> isDirectProp = DIRECT_PROPS_REGEX.test sourceCode.getText node isDirectNextProp = DIRECT_NEXT_PROPS_REGEX.test sourceCode.getText node isDirectPrevProp = DIRECT_PREV_PROPS_REGEX.test sourceCode.getText node isDirectSetStateProp = isPropArgumentInSetStateUpdater node isInClassComponent = utils.getParentES6Component() or utils.getParentES5Component() isNotInConstructor = not inConstructor node isNotInLifeCycleMethod = not inLifeCycleMethod() isNotInSetStateUpdater = not inSetStateUpdater() return undefined if ( (isDirectProp or isDirectNextProp or isDirectPrevProp or isDirectSetStateProp) and isInClassComponent and isNotInConstructor and isNotInLifeCycleMethod and isNotInSetStateUpdater ) if ( not isDirectProp and not isDirectNextProp and not isDirectPrevProp and not isDirectSetStateProp ) node = node.parent {property} = node if property switch property.type when 'Identifier' return '__COMPUTED_PROP__' if node.computed return property.name when 'MemberExpression' return undefined when 'Literal' # Accept computed properties that are literal strings return property.value if typeof property.value is 'string' return '__COMPUTED_PROP__' if node.computed else return '__COMPUTED_PROP__' if node.computed undefined ###* # Mark a prop type as used # @param {ASTNode} node The AST node being marked. ### markPropTypesAsUsed = (node, parentNames) -> parentNames or= [] switch node.type when 'MemberExpression' name = getPropertyName node if name allNames = parentNames.concat name if node.parent.type is 'MemberExpression' markPropTypesAsUsed node.parent, allNames # Do not mark computed props as used. type = unless name is '__COMPUTED_PROP__' then 'direct' else null else left = node.parent.id ? node.parent.left if left?.properties?.length and getKeyValue left.properties[0] type = 'destructuring' {properties} = left when 'ArrowFunctionExpression', 'FunctionDeclaration', 'FunctionExpression' break unless node.params.length type = 'destructuring' {properties} = node.params[0] {properties} = node.params[1] ? {} if inSetStateUpdater() when 'VariableDeclarator', 'AssignmentExpression' left = node.id ? node.left # let {props: {firstname}} = this # let {firstname} = props for property in left.properties thisDestructuring = property.key and ((property.key.name is 'props' or property.key.value is 'props') and property.value.type is 'ObjectPattern') genericDestructuring = isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) if thisDestructuring {properties} = property.value else if genericDestructuring {properties} = left else continue type = 'destructuring' else throw new Error( "#{node.type} ASTNodes are not handled by markPropTypesAsUsed" ) component = components.get utils.getParentComponent() usedPropTypes = component?.usedPropTypes or [] ignoreUnusedPropTypesValidation = component?.ignoreUnusedPropTypesValidation or no switch type when 'direct' # Ignore Object methods break if Object::[name] usedPropTypes.push { name allNames } when 'destructuring' for property in properties or [] if hasSpreadOperator(property) or property.computed ignoreUnusedPropTypesValidation = yes propName = getKeyValue property currentNode = node allNames = [] while ( currentNode.property and currentNode.property.name isnt 'props' ) allNames.unshift currentNode.property.name currentNode = currentNode.object allNames.push propName if propName usedPropTypes.push { allNames name: propName } components.set component?.node ? node, { usedPropTypes ignoreUnusedPropTypesValidation } ###* # Used to recursively loop through each declared prop type # @param {Object} component The component to process # @param {Array} props List of props to validate ### reportUnusedPropType = (component, props) -> # Skip props that check instances return if props is yes Object.keys(props or {}).forEach (key) -> prop = props[key] # Skip props that check instances return if prop is yes return if prop.type is 'shape' and configuration.skipShapeProps if prop.node and not isPropUsed component, prop context.report prop.node, UNUSED_MESSAGE, name: prop.fullName if prop.children then reportUnusedPropType component, prop.children ###* # Reports unused proptypes for a given component # @param {Object} component The component to process ### reportUnusedPropTypes = (component) -> reportUnusedPropType component, component.declaredPropTypes ###* # @param {ASTNode} node We expect either an ArrowFunctionExpression, # FunctionDeclaration, or FunctionExpression ### markDestructuredFunctionArgumentsAsUsed = (node) -> destructuring = node.params?[0]?.type is 'ObjectPattern' if destructuring and components.get node then markPropTypesAsUsed node handleSetStateUpdater = (node) -> return unless node.params?.length >= 2 and inSetStateUpdater() markPropTypesAsUsed node ###* # Handle both stateless functions and setState updater functions. # @param {ASTNode} node We expect either an ArrowFunctionExpression, # FunctionDeclaration, or FunctionExpression ### handleFunctionLikeExpressions = (node) -> handleSetStateUpdater node markDestructuredFunctionArgumentsAsUsed node handleCustomValidators = (component) -> propTypes = component.declaredPropTypes return unless propTypes Object.keys(propTypes).forEach (key) -> {node} = propTypes[key] if astUtil.isFunctionLikeExpression node then markPropTypesAsUsed node # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- VariableDeclarator: (node) -> destructuring = node.init and node.id and node.id.type is 'ObjectPattern' # let {props: {firstname}} = this thisDestructuring = destructuring and node.init.type is 'ThisExpression' # let {firstname} = props statelessDestructuring = destructuring and isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) return if not thisDestructuring and not statelessDestructuring markPropTypesAsUsed node AssignmentExpression: (node) -> destructuring = node.left.type is 'ObjectPattern' # let {props: {firstname}} = this thisDestructuring = destructuring and node.right.type is 'ThisExpression' # let {firstname} = props statelessDestructuring = destructuring and isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) return unless thisDestructuring or statelessDestructuring markPropTypesAsUsed node FunctionDeclaration: handleFunctionLikeExpressions ArrowFunctionExpression: handleFunctionLikeExpressions FunctionExpression: handleFunctionLikeExpressions MemberExpression: (node) -> markPropTypesAsUsed node if isPropTypesUsage node ObjectPattern: (node) -> # If the object pattern is a destructured props object in a lifecycle # method -- mark it for used props. if isNodeALifeCycleMethod node.parent.parent node.properties.forEach (property, i) -> if i is 0 then markPropTypesAsUsed node.parent 'Program:exit': -> list = components.list() # Report undeclared proptypes for all classes for own _, component of list when mustBeValidated component handleCustomValidators component reportUnusedPropTypes component
true
###* # @fileoverview Prevent definitions of unused prop types # @author PI:NAME:<NAME>END_PI ### 'use strict' # As for exceptions for props.children or props.className (and alike) look at # https://github.com/yannickcr/eslint-plugin-react/issues/7 Components = require '../util/react/Components' astUtil = require '../util/react/ast' versionUtil = require 'eslint-plugin-react/lib/util/version' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Constants # ------------------------------------------------------------------------------ DIRECT_PROPS_REGEX = /^props\s*(\.|\[)/ DIRECT_NEXT_PROPS_REGEX = /^nextProps\s*(\.|\[)/ DIRECT_PREV_PROPS_REGEX = /^prevProps\s*(\.|\[)/ LIFE_CYCLE_METHODS = [ 'componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'componentDidUpdate' ] ASYNC_SAFE_LIFE_CYCLE_METHODS = [ 'getDerivedStateFromProps' 'getSnapshotBeforeUpdate' 'UNSAFE_componentWillReceiveProps' 'UNSAFE_componentWillUpdate' ] # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Prevent definitions of unused prop types' category: 'Best Practices' recommended: no url: docsUrl 'no-unused-prop-types' schema: [ type: 'object' properties: customValidators: type: 'array' items: type: 'string' skipShapeProps: type: 'boolean' additionalProperties: no ] create: Components.detect (context, components, utils) -> sourceCode = context.getSourceCode() checkAsyncSafeLifeCycles = versionUtil.testReactVersion context, '16.3.0' defaults = skipShapeProps: yes, customValidators: [] configuration = {...defaults, ...(context.options[0] or {})} UNUSED_MESSAGE = "'{{name}}' PropType is defined but prop is never used" # ###* # Check if we are in a lifecycle method # @return {boolean} true if we are in a class constructor, false if not ### inLifeCycleMethod = -> scope = context.getScope() while scope if scope.block?.parent?.key {name} = scope.block.parent.key return yes if LIFE_CYCLE_METHODS.indexOf(name) >= 0 return yes if ( checkAsyncSafeLifeCycles and ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(name) >= 0 ) scope = scope.upper no ###* # Check if the current node is in a setState updater method # @return {boolean} true if we are in a setState updater, false if not ### inSetStateUpdater = -> scope = context.getScope() while scope return yes if ( scope.block?.parent?.type is 'CallExpression' and scope.block.parent.callee.property?.name is 'setState' and # Make sure we are in the updater not the callback scope.block.parent.arguments[0].start is scope.block.start ) scope = scope.upper no isPropArgumentInSetStateUpdater = (node) -> scope = context.getScope() while scope return ( scope.block.parent.arguments[0].params[1].name is node.object.name ) if ( scope.block?.parent and scope.block.parent.type is 'CallExpression' and scope.block.parent.callee.property and scope.block.parent.callee.property.name is 'setState' and # Make sure we are in the updater not the callback scope.block.parent.arguments[0].start is scope.block.start and scope.block.parent.arguments[0].params and scope.block.parent.arguments[0].params.length > 1 ) scope = scope.upper no ###* # Checks if we are using a prop # @param {ASTNode} node The AST node being checked. # @returns {Boolean} True if we are using a prop, false if not. ### isPropTypesUsage = (node) -> isClassUsage = (utils.getParentES6Component() or utils.getParentES5Component()) and ((node.object.type is 'ThisExpression' and node.property.name is 'props') or isPropArgumentInSetStateUpdater node) isStatelessFunctionUsage = node.object.name is 'props' isClassUsage or isStatelessFunctionUsage or inLifeCycleMethod() ###* # Checks if the component must be validated # @param {Object} component The component to process # @returns {Boolean} True if the component must be validated, false if not. ### mustBeValidated = (component) -> Boolean component and not component.ignoreUnusedPropTypesValidation ###* # Returns true if the given node is a React Component lifecycle method # @param {ASTNode} node The AST node being checked. # @return {Boolean} True if the node is a lifecycle method ### isNodeALifeCycleMethod = (node) -> nodeKeyName = node.key?.name return yes if node.kind is 'constructor' return yes if LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0 return yes if ( checkAsyncSafeLifeCycles and ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0 ) no ###* # Returns true if the given node is inside a React Component lifecycle # method. # @param {ASTNode} node The AST node being checked. # @return {Boolean} True if the node is inside a lifecycle method ### isInLifeCycleMethod = (node) -> return yes if ( node.type in ['MethodDefinition', 'Property'] and isNodeALifeCycleMethod node ) return isInLifeCycleMethod node.parent if node.parent no ###* # Checks if a prop init name matches common naming patterns # @param {ASTNode} node The AST node being checked. # @returns {Boolean} True if the prop name matches ### isPropAttributeName = (node) -> (node.init ? node.right).name in ['props', 'nextProps', 'prevProps'] ###* # Checks if a prop is used # @param {ASTNode} node The AST node being checked. # @param {Object} prop Declared prop object # @returns {Boolean} True if the prop is used, false if not. ### isPropUsed = (node, prop) -> usedPropTypes = node.usedPropTypes or [] i = 0 l = usedPropTypes.length while i < l usedProp = usedPropTypes[i] return yes if ( prop.type is 'shape' or prop.name is '__ANY_KEY__' or usedProp.name is prop.name ) i++ no ###* # Checks if the prop has spread operator. # @param {ASTNode} node The AST node being marked. # @returns {Boolean} True if the prop has spread operator, false if not. ### hasSpreadOperator = (node) -> tokens = sourceCode.getTokens node tokens.length and tokens[0].value is '...' ###* # Removes quotes from around an identifier. # @param {string} the identifier to strip ### stripQuotes = (string) -> string.replace /^'|'$/g, '' ###* # Retrieve the name of a key node # @param {ASTNode} node The AST node with the key. # @return {string} the name of the key ### getKeyValue = (node) -> if node.type is 'ObjectTypeProperty' tokens = context.getFirstTokens node, 2 return ( if tokens[0].value in ['+', '-'] tokens[1].value else stripQuotes tokens[0].value ) key = node.key or node.argument if key.type is 'Identifier' then key.name else key.value ###* # Check if we are in a class constructor # @return {boolean} true if we are in a class constructor, false if not ### inConstructor = -> scope = context.getScope() while scope return yes if ( scope.block?.parent and scope.block.parent.kind is 'constructor' ) scope = scope.upper no ###* # Retrieve the name of a property node # @param {ASTNode} node The AST node with the property. # @return {string} the name of the property or undefined if not found ### getPropertyName = (node) -> isDirectProp = DIRECT_PROPS_REGEX.test sourceCode.getText node isDirectNextProp = DIRECT_NEXT_PROPS_REGEX.test sourceCode.getText node isDirectPrevProp = DIRECT_PREV_PROPS_REGEX.test sourceCode.getText node isDirectSetStateProp = isPropArgumentInSetStateUpdater node isInClassComponent = utils.getParentES6Component() or utils.getParentES5Component() isNotInConstructor = not inConstructor node isNotInLifeCycleMethod = not inLifeCycleMethod() isNotInSetStateUpdater = not inSetStateUpdater() return undefined if ( (isDirectProp or isDirectNextProp or isDirectPrevProp or isDirectSetStateProp) and isInClassComponent and isNotInConstructor and isNotInLifeCycleMethod and isNotInSetStateUpdater ) if ( not isDirectProp and not isDirectNextProp and not isDirectPrevProp and not isDirectSetStateProp ) node = node.parent {property} = node if property switch property.type when 'Identifier' return '__COMPUTED_PROP__' if node.computed return property.name when 'MemberExpression' return undefined when 'Literal' # Accept computed properties that are literal strings return property.value if typeof property.value is 'string' return '__COMPUTED_PROP__' if node.computed else return '__COMPUTED_PROP__' if node.computed undefined ###* # Mark a prop type as used # @param {ASTNode} node The AST node being marked. ### markPropTypesAsUsed = (node, parentNames) -> parentNames or= [] switch node.type when 'MemberExpression' name = getPropertyName node if name allNames = parentNames.concat name if node.parent.type is 'MemberExpression' markPropTypesAsUsed node.parent, allNames # Do not mark computed props as used. type = unless name is '__COMPUTED_PROP__' then 'direct' else null else left = node.parent.id ? node.parent.left if left?.properties?.length and getKeyValue left.properties[0] type = 'destructuring' {properties} = left when 'ArrowFunctionExpression', 'FunctionDeclaration', 'FunctionExpression' break unless node.params.length type = 'destructuring' {properties} = node.params[0] {properties} = node.params[1] ? {} if inSetStateUpdater() when 'VariableDeclarator', 'AssignmentExpression' left = node.id ? node.left # let {props: {firstname}} = this # let {firstname} = props for property in left.properties thisDestructuring = property.key and ((property.key.name is 'props' or property.key.value is 'props') and property.value.type is 'ObjectPattern') genericDestructuring = isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) if thisDestructuring {properties} = property.value else if genericDestructuring {properties} = left else continue type = 'destructuring' else throw new Error( "#{node.type} ASTNodes are not handled by markPropTypesAsUsed" ) component = components.get utils.getParentComponent() usedPropTypes = component?.usedPropTypes or [] ignoreUnusedPropTypesValidation = component?.ignoreUnusedPropTypesValidation or no switch type when 'direct' # Ignore Object methods break if Object::[name] usedPropTypes.push { name allNames } when 'destructuring' for property in properties or [] if hasSpreadOperator(property) or property.computed ignoreUnusedPropTypesValidation = yes propName = getKeyValue property currentNode = node allNames = [] while ( currentNode.property and currentNode.property.name isnt 'props' ) allNames.unshift currentNode.property.name currentNode = currentNode.object allNames.push propName if propName usedPropTypes.push { allNames name: propName } components.set component?.node ? node, { usedPropTypes ignoreUnusedPropTypesValidation } ###* # Used to recursively loop through each declared prop type # @param {Object} component The component to process # @param {Array} props List of props to validate ### reportUnusedPropType = (component, props) -> # Skip props that check instances return if props is yes Object.keys(props or {}).forEach (key) -> prop = props[key] # Skip props that check instances return if prop is yes return if prop.type is 'shape' and configuration.skipShapeProps if prop.node and not isPropUsed component, prop context.report prop.node, UNUSED_MESSAGE, name: prop.fullName if prop.children then reportUnusedPropType component, prop.children ###* # Reports unused proptypes for a given component # @param {Object} component The component to process ### reportUnusedPropTypes = (component) -> reportUnusedPropType component, component.declaredPropTypes ###* # @param {ASTNode} node We expect either an ArrowFunctionExpression, # FunctionDeclaration, or FunctionExpression ### markDestructuredFunctionArgumentsAsUsed = (node) -> destructuring = node.params?[0]?.type is 'ObjectPattern' if destructuring and components.get node then markPropTypesAsUsed node handleSetStateUpdater = (node) -> return unless node.params?.length >= 2 and inSetStateUpdater() markPropTypesAsUsed node ###* # Handle both stateless functions and setState updater functions. # @param {ASTNode} node We expect either an ArrowFunctionExpression, # FunctionDeclaration, or FunctionExpression ### handleFunctionLikeExpressions = (node) -> handleSetStateUpdater node markDestructuredFunctionArgumentsAsUsed node handleCustomValidators = (component) -> propTypes = component.declaredPropTypes return unless propTypes Object.keys(propTypes).forEach (key) -> {node} = propTypes[key] if astUtil.isFunctionLikeExpression node then markPropTypesAsUsed node # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- VariableDeclarator: (node) -> destructuring = node.init and node.id and node.id.type is 'ObjectPattern' # let {props: {firstname}} = this thisDestructuring = destructuring and node.init.type is 'ThisExpression' # let {firstname} = props statelessDestructuring = destructuring and isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) return if not thisDestructuring and not statelessDestructuring markPropTypesAsUsed node AssignmentExpression: (node) -> destructuring = node.left.type is 'ObjectPattern' # let {props: {firstname}} = this thisDestructuring = destructuring and node.right.type is 'ThisExpression' # let {firstname} = props statelessDestructuring = destructuring and isPropAttributeName(node) and (utils.getParentStatelessComponent() or isInLifeCycleMethod node) return unless thisDestructuring or statelessDestructuring markPropTypesAsUsed node FunctionDeclaration: handleFunctionLikeExpressions ArrowFunctionExpression: handleFunctionLikeExpressions FunctionExpression: handleFunctionLikeExpressions MemberExpression: (node) -> markPropTypesAsUsed node if isPropTypesUsage node ObjectPattern: (node) -> # If the object pattern is a destructured props object in a lifecycle # method -- mark it for used props. if isNodeALifeCycleMethod node.parent.parent node.properties.forEach (property, i) -> if i is 0 then markPropTypesAsUsed node.parent 'Program:exit': -> list = components.list() # Report undeclared proptypes for all classes for own _, component of list when mustBeValidated component handleCustomValidators component reportUnusedPropTypes component
[ { "context": "sers =\n 14: {request: 14, id: 21, name: 'Josh'}\n 12: {request: 12, id: 25, name: 'Leo'", "end": 17939, "score": 0.9997209310531616, "start": 17935, "tag": "NAME", "value": "Josh" }, { "context": "Josh'}\n 12: {request: 12, id: 25, name: 'Leo'}\n 34: {request: 34, id: 84, name: 'Anic", "end": 17988, "score": 0.9997867345809937, "start": 17985, "tag": "NAME", "value": "Leo" }, { "context": "'Leo'}\n 34: {request: 34, id: 84, name: 'Anica'}\n messages =\n 34: {request: 34, ", "end": 18039, "score": 0.9997615218162537, "start": 18034, "tag": "NAME", "value": "Anica" }, { "context": "ocessing logic here\n if payload.name is 'DelayLama'\n # oops\n c.outPorts.saved.", "end": 50732, "score": 0.9834794998168945, "start": 50723, "tag": "USERNAME", "value": "DelayLama" }, { "context": " done()\n\n form.send\n name: 'Bo'\n email: 'missing'\n form.disconne", "end": 51875, "score": 0.9918138980865479, "start": 51873, "tag": "NAME", "value": "Bo" }, { "context": " done data\n\n form.send\n name: 'Josh'\n email: 'josh@example.com'\n ac", "end": 52372, "score": 0.9994065761566162, "start": 52368, "tag": "NAME", "value": "Josh" }, { "context": "orm.send\n name: 'Josh'\n email: 'josh@example.com'\n accept: true\n form.disconnect()", "end": 52408, "score": 0.9999266266822815, "start": 52392, "tag": "EMAIL", "value": "josh@example.com" }, { "context": " done()\n\n form.send\n name: 'DelayLama'\n email: 'delay@lama.ti'\n accep", "end": 52966, "score": 0.9906700253486633, "start": 52957, "tag": "NAME", "value": "DelayLama" }, { "context": "end\n name: 'DelayLama'\n email: 'delay@lama.ti'\n accept: true\n form.disconnect()", "end": 52999, "score": 0.999930739402771, "start": 52986, "tag": "EMAIL", "value": "delay@lama.ti" }, { "context": "ocessing logic here\n if payload.name is 'DelayLama'\n # oops\n out.send false\n ", "end": 54655, "score": 0.8732151389122009, "start": 54646, "tag": "USERNAME", "value": "DelayLama" }, { "context": " form.post new noflo.IP 'data',\n name: 'Bo'\n email: 'missing'\n , scope: 'foo", "end": 55948, "score": 0.9986352324485779, "start": 55946, "tag": "NAME", "value": "Bo" }, { "context": " done data\n\n form.send\n name: 'Josh'\n email: 'josh@example.com'\n ac", "end": 56540, "score": 0.9994010329246521, "start": 56536, "tag": "NAME", "value": "Josh" }, { "context": "orm.send\n name: 'Josh'\n email: 'josh@example.com'\n accept: true\n form.disconnect()", "end": 56576, "score": 0.9999251961708069, "start": 56560, "tag": "EMAIL", "value": "josh@example.com" }, { "context": " done()\n\n form.send\n name: 'DelayLama'\n email: 'delay@lama.ti'\n accep", "end": 57308, "score": 0.9062697291374207, "start": 57299, "tag": "NAME", "value": "DelayLama" }, { "context": "end\n name: 'DelayLama'\n email: 'delay@lama.ti'\n accept: true\n form.disconnect()", "end": 57341, "score": 0.9999300241470337, "start": 57328, "tag": "EMAIL", "value": "delay@lama.ti" }, { "context": " c2.inPorts.name.attach ins\n\n ins.send 'Norman'\n chai.expect(c2.hasErrors).to.be.true\n ", "end": 57832, "score": 0.9995953440666199, "start": 57826, "tag": "NAME", "value": "Norman" } ]
spec/Helpers.coffee
aretecode/noflo-built
1
if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/ chai = require 'chai' unless chai noflo = require '../src/lib/NoFlo.coffee' else noflo = require 'noflo' describe 'Component traits', -> describe 'MapComponent', -> c = null it 'should pass data to the callback', -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data) -> chai.expect(data).to.equal 1 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s.send 1 it 'should pass groups to the callback', -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data, groups) -> chai.expect(groups).to.eql [ 'one' 'two' ] chai.expect(data).to.equal 1 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s.beginGroup 'one' s.beginGroup 'two' s.send 1 it 'should send groups and disconnect through', (done) -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data, groups, out) -> out.send data * 2 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s2 = new noflo.internalSocket.createSocket() c.outPorts.out.attach s2 groups = [] s2.on 'begingroup', (group) -> groups.push group s2.on 'data', (data) -> chai.expect(groups.length).to.equal 2 chai.expect(data).to.equal 6 s2.on 'endgroup', -> groups.pop() s2.on 'disconnect', -> chai.expect(groups.length).to.equal 0 done() s.beginGroup 'one' s.beginGroup 'two' s.send 3 s.endGroup() s.endGroup() s.disconnect() describe 'WirePattern', -> describe 'when grouping by packet groups', -> c = null x = null y = null z = null p = null before (done) -> c = new noflo.Component c.inPorts.add 'x', required: true datatype: 'int' .add 'y', required: true datatype: 'int' .add 'z', required: true datatype: 'int' c.outPorts.add 'point' x = new noflo.internalSocket.createSocket() y = new noflo.internalSocket.createSocket() z = new noflo.internalSocket.createSocket() p = new noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.inPorts.z.attach z c.outPorts.point.attach p done() it 'should pass data and groups to the callback', (done) -> src = 111: {x: 1, y: 2, z: 3} 222: {x: 4, y: 5, z: 6} 333: {x: 7, y: 8, z: 9} noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' group: true forwardGroups: true , (data, groups, out) -> chai.expect(groups.length).to.be.above 0 chai.expect(data).to.deep.equal src[groups[0]] out.send data groups = [] count = 0 p.on 'begingroup', (grp) -> groups.push grp p.on 'endgroup', -> groups.pop() p.on 'data', (data) -> count++ p.on 'disconnect', -> done() if count is 3 and groups.length is 0 for key, grp of src x.beginGroup key y.beginGroup key z.beginGroup key x.send grp.x y.send grp.y z.send grp.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should work without a group provided', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' , (data, groups, out) -> chai.expect(groups.length).to.equal 0 out.send {x: data.x, y: data.y, z: data.z} p.once 'data', (data) -> chai.expect(data).to.deep.equal {x: 123, y: 456, z: 789} done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() it 'should process inputs for different groups independently with group: true', (done) -> src = 1: {x: 1, y: 2, z: 3} 2: {x: 4, y: 5, z: 6} 3: {x: 7, y: 8, z: 9} inOrder = [ [ 1, 'x' ] [ 3, 'z' ] [ 2, 'y' ] [ 2, 'x' ] [ 1, 'z' ] [ 2, 'z' ] [ 3, 'x' ] [ 1, 'y' ] [ 3, 'y' ] ] outOrder = [ 2, 1, 3 ] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' group: true forwardGroups: true , (data, groups, out) -> out.send {x: data.x, y: data.y, z: data.z} groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'endgroup', (grp) -> groups.pop() p.on 'data', (data) -> chai.expect(groups.length).to.equal 1 chai.expect(groups[0]).to.equal outOrder[0] chai.expect(data).to.deep.equal src[outOrder[0]] outOrder.shift() done() unless outOrder.length for tuple in inOrder input = null switch tuple[1] when 'x' input = x when 'y' input = y when 'z' input = z input.beginGroup tuple[0] input.send src[tuple[0]][tuple[1]] input.endGroup() input.disconnect() it 'should support asynchronous handlers', (done) -> point = x: 123 y: 456 z: 789 noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' async: true group: true forwardGroups: true , (data, groups, out, callback) -> setTimeout -> out.send {x: data.x, y: data.y, z: data.z} callback() , 100 p.removeAllListeners() counter = 0 hadData = false p.on 'begingroup', (grp) -> counter++ p.on 'endgroup', -> counter-- p.once 'data', (data) -> chai.expect(data).to.deep.equal point hadData = true p.once 'disconnect', -> chai.expect(counter).to.equal 0 chai.expect(hadData).to.be.true done() x.beginGroup 'async' y.beginGroup 'async' z.beginGroup 'async' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should not forward groups if forwarding is off', (done) -> point = x: 123 y: 456 noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'point' , (data, groups, out) -> out.send { x: data.x, y: data.y } p.removeAllListeners() counter = 0 hadData = false p.on 'begingroup', (grp) -> counter++ p.on 'data', (data) -> chai.expect(data).to.deep.equal point hadData = true p.once 'disconnect', -> chai.expect(counter).to.equal 0 chai.expect(hadData).to.be.true done() x.beginGroup 'doNotForwardMe' y.beginGroup 'doNotForwardMe' x.send point.x y.send point.y x.endGroup() y.endGroup() x.disconnect() y.disconnect() it 'should forward groups from a specific port only', (done) -> point = x: 123 y: 456 z: 789 refGroups = ['boo'] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' forwardGroups: 'y' , (data, groups, out) -> out.send { x: data.x, y: data.y, z: data.z } p.removeAllListeners() groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'data', (data) -> chai.expect(data).to.deep.equal point p.once 'disconnect', -> chai.expect(groups).to.deep.equal refGroups done() x.beginGroup 'foo' y.beginGroup 'boo' z.beginGroup 'bar' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should forward groups from selected ports only', (done) -> point = x: 123 y: 456 z: 789 refGroups = ['foo', 'bar'] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' forwardGroups: [ 'x', 'z' ] , (data, groups, out) -> out.send { x: data.x, y: data.y, z: data.z } p.removeAllListeners() groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'data', (data) -> chai.expect(data).to.deep.equal point p.once 'disconnect', -> chai.expect(groups).to.deep.equal refGroups done() x.beginGroup 'foo' y.beginGroup 'boo' z.beginGroup 'bar' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() describe 'when `this` context is important', -> c = new noflo.Component c.inPorts.add 'x', required: true datatype: 'int' .add 'y', required: true datatype: 'int' .add 'z', required: true datatype: 'int' c.outPorts.add 'point' x = new noflo.internalSocket.createSocket() y = new noflo.internalSocket.createSocket() z = new noflo.internalSocket.createSocket() p = new noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.inPorts.z.attach z c.outPorts.point.attach p it 'should correctly bind component to `this` context', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' , (data, groups, out) -> chai.expect(this).to.deep.equal c out.send {x: data.x, y: data.y, z: data.z} p.once 'data', (data) -> chai.expect(data).to.deep.equal {x: 123, y: 456, z: 789} done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() it 'should correctly bind component to `this` context in async mode', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] async: true out: 'point' , (data, groups, out, callback) -> chai.expect(this).to.deep.equal c out.send {x: data.x, y: data.y, z: data.z} callback() p.once 'data', (data) -> done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() describe 'when in async mode and packet order matters', -> c = new noflo.Component c.inPorts.add 'delay', datatype: 'int' .add 'msg', datatype: 'string' c.outPorts.add 'out', datatype: 'object' .add 'load', datatype: 'int' delay = new noflo.internalSocket.createSocket() msg = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() load = new noflo.internalSocket.createSocket() c.inPorts.delay.attach delay c.inPorts.msg.attach msg c.outPorts.out.attach out c.outPorts.load.attach load it 'should preserve input order at the output', (done) -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false , (data, groups, res, callback) -> setTimeout -> res.send { delay: data.delay, msg: data.msg } callback() , data.delay sample = [ { delay: 30, msg: "one" } { delay: 0, msg: "two" } { delay: 20, msg: "three" } { delay: 10, msg: "four" } ] out.on 'data', (data) -> chai.expect(data).to.deep.equal sample.shift() out.on 'disconnect', -> done() if sample.length is 0 expected = [1, 2, 3, 4, 3, 2, 1, 0] load.on 'data', (data) -> chai.expect(data).to.equal expected.shift() idx = 0 for ip in sample delay.beginGroup idx delay.send ip.delay delay.endGroup() msg.beginGroup idx msg.send ip.msg msg.endGroup() delay.disconnect() msg.disconnect() idx++ it 'should throw if receiveStreams is used', (done) -> f = -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false receiveStreams: ['delay', 'msg'] , (data, groups, res, callback) -> callback() chai.expect(f).to.throw Error done() it 'should throw if sendStreams is used', (done) -> f = -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false sendStreams: ['out'] , (data, groups, res, callback) -> callback() chai.expect(f).to.throw Error done() # it 'should support complex substreams', (done) -> # out.removeAllListeners() # load.removeAllListeners() # c.cntr = 0 # helpers.WirePattern c, # in: ['delay', 'msg'] # async: true # ordered: true # group: false # receiveStreams: ['delay', 'msg'] # , (data, groups, res, callback) -> # # Substream to object conversion validation # # (the hard way) # chai.expect(data.delay instanceof Substream).to.be.true # chai.expect(data.msg instanceof Substream).to.be.true # delayObj = data.delay.toObject() # msgObj = data.msg.toObject() # index0 = this.cntr.toString() # chai.expect(Object.keys(delayObj)[0]).to.equal index0 # chai.expect(Object.keys(msgObj)[0]).to.equal index0 # subDelay = delayObj[index0] # subMsg = msgObj[index0] # index1 = (10 + this.cntr).toString() # chai.expect(Object.keys(subDelay)[0]).to.equal index1 # chai.expect(Object.keys(subMsg)[0]).to.equal index1 # delayData = subDelay[index1] # msgData = subMsg[index1] # chai.expect(delayData).to.equal sample[c.cntr].delay # chai.expect(msgData).to.equal sample[c.cntr].msg # this.cntr++ # setTimeout -> # # Substream tree traversal (the easy way) # for k0, v0 of msgObj # res.beginGroup k0 # res.send k0 # for k1, v1 of v0 # res.beginGroup k1 # res.send # delay: delayObj[k0][k1] # msg: msgObj[k0][k1] # res.endGroup() # res.send k1 # res.endGroup() # callback() # , data.delay # sample = [ # { delay: 30, msg: "one" } # { delay: 0, msg: "two" } # { delay: 20, msg: "three" } # { delay: 10, msg: "four" } # ] # expected = [ # '0', '0', '10', sample[0], '10' # '1', '1', '11', sample[1], '11' # '2', '2', '12', sample[2], '12' # '3', '3', '13', sample[3], '13' # ] # out.on 'begingroup', (grp) -> # chai.expect(grp).to.equal expected.shift() # out.on 'data', (data) -> # chai.expect(data).to.deep.equal expected.shift() # out.on 'disconnect', -> # done() if expected.length is 0 # for i in [0..3] # delay.beginGroup i # delay.beginGroup 10 + i # delay.send sample[i].delay # delay.endGroup() # delay.endGroup() # msg.beginGroup i # msg.beginGroup 10 + i # msg.send sample[i].msg # msg.endGroup() # msg.endGroup() # delay.disconnect() # msg.disconnect() describe 'when grouping by field', -> c = new noflo.Component c.inPorts.add 'user', datatype: 'object' .add 'message', datatype: 'object' c.outPorts.add 'signedmessage' usr = new noflo.internalSocket.createSocket() msg = new noflo.internalSocket.createSocket() umsg = new noflo.internalSocket.createSocket() c.inPorts.user.attach usr c.inPorts.message.attach msg c.outPorts.signedmessage.attach umsg it 'should match objects by specific field', (done) -> noflo.helpers.WirePattern c, in: ['user', 'message'] out: 'signedmessage' async: true field: 'request' , (data, groups, out, callback) -> setTimeout -> out.send request: data.request user: data.user.name text: data.message.text callback() , 10 users = 14: {request: 14, id: 21, name: 'Josh'} 12: {request: 12, id: 25, name: 'Leo'} 34: {request: 34, id: 84, name: 'Anica'} messages = 34: {request: 34, id: 234, text: 'Hello world'} 12: {request: 12, id: 82, text: 'Aloha amigos'} 14: {request: 14, id: 249, text: 'Node.js ftw'} counter = 0 umsg.on 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.request).to.be.ok chai.expect(data.user).to.equal users[data.request].name chai.expect(data.text).to.equal messages[data.request].text counter++ done() if counter is 3 # Send input asynchronously with mixed delays for req, user of users do (req, user) -> setTimeout -> usr.send user usr.disconnect() , req for req, mesg of messages do (req, mesg) -> setTimeout -> msg.send mesg msg.disconnect() , req describe 'when there are multiple output routes', -> c = new noflo.Component c.inPorts.add 'num', datatype: 'int' .add 'str', datatype: 'string' c.outPorts.add 'odd', datatype: 'object' .add 'even', datatype: 'object' num = new noflo.internalSocket.createSocket() str = new noflo.internalSocket.createSocket() odd = new noflo.internalSocket.createSocket() even = new noflo.internalSocket.createSocket() c.inPorts.num.attach num c.inPorts.str.attach str c.outPorts.odd.attach odd c.outPorts.even.attach even it 'should send output to one or more of them', (done) -> numbers = ['cero', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'] noflo.helpers.WirePattern c, in: ['num', 'str'] out: ['odd', 'even'] async: true ordered: true , (data, groups, outs, callback) -> setTimeout -> if data.num % 2 is 1 outs.odd.beginGroup grp for grp in groups outs.odd.send data outs.odd.endGroup() for grp in groups else outs.even.beginGroup grp for grp in groups outs.even.send data outs.even.endGroup() for grp in groups callback() , 0 grpCounter = 0 dataCounter = 0 odd.on 'begingroup', (grp) -> grpCounter++ odd.on 'data', (data) -> chai.expect(data.num % 2).to.equal 1 chai.expect(data.str).to.equal numbers[data.num] dataCounter++ odd.on 'disconnect', -> done() if dataCounter is 10 and grpCounter is 10 even.on 'begingroup', (grp) -> grpCounter++ even.on 'data', (data) -> chai.expect(data.num % 2).to.equal 0 chai.expect(data.str).to.equal numbers[data.num] dataCounter++ even.on 'disconnect', -> done() if dataCounter is 10 and grpCounter is 10 for i in [0...10] num.beginGroup i num.send i num.endGroup i num.disconnect() str.beginGroup i str.send numbers[i] str.endGroup i str.disconnect() describe 'when there are parameter ports', -> c = null p1 = p2 = p3 = d1 = d2 = out = err = 0 beforeEach -> c = new noflo.Component c.inPorts.add 'param1', datatype: 'string' required: true .add 'param2', datatype: 'int' required: false .add 'param3', datatype: 'int' required: true default: 0 .add 'data1', datatype: 'string' .add 'data2', datatype: 'int' c.outPorts.add 'out', datatype: 'object' .add 'error', datatype: 'object' p1 = new noflo.internalSocket.createSocket() p2 = new noflo.internalSocket.createSocket() p3 = new noflo.internalSocket.createSocket() d1 = new noflo.internalSocket.createSocket() d2 = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.param1.attach p1 c.inPorts.param2.attach p2 c.inPorts.param3.attach p3 c.inPorts.data1.attach d1 c.inPorts.data2.attach d2 c.outPorts.out.attach out c.outPorts.error.attach err it 'should wait for required params without default value', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.be.undefined chai.expect(data.p3).to.equal 0 chai.expect(data.d1).to.equal 'foo' chai.expect(data.d2).to.equal 123 # And later when second param arrives out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 568 chai.expect(data.p3).to.equal 800 chai.expect(data.d1).to.equal 'bar' chai.expect(data.d2).to.equal 456 done() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() c.sendDefaults() p1.send 'req' p1.disconnect() # the handler should be triggered here setTimeout -> p2.send 568 p2.disconnect() p3.send 800 p3.disconnect() d1.send 'bar' d1.disconnect() d2.send 456 d2.disconnect() , 10 it 'should work for async procs too', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> delay = if c.params.param2 then c.params.param2 else 10 setTimeout -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res , delay out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 56 chai.expect(data.p3).to.equal 0 chai.expect(data.d1).to.equal 'foo' chai.expect(data.d2).to.equal 123 done() p2.send 56 p2.disconnect() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() c.sendDefaults() p1.send 'req' p1.disconnect() # the handler should be triggered here it 'should reset state if shutdown() is called', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> out.send p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 d1.send 'boo' d1.disconnect() p2.send 73 p2.disconnect() chai.expect(Object.keys(c._wpData[null].groupedData)).to.have.length.above 0 chai.expect(Object.keys(c._wpData[null].params)).to.have.length.above 0 c.shutdown() chai.expect(c._wpData).to.deep.equal {} done() it 'should drop premature data if configured to do so', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] dropInput: true , (input, groups, out) -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 568 chai.expect(data.p3).to.equal 800 chai.expect(data.d1).to.equal 'bar' chai.expect(data.d2).to.equal 456 done() c.sendDefaults() p2.send 568 p2.disconnect() p3.send 800 p3.disconnect() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() # Data is dropped at this point setTimeout -> p1.send 'req' p1.disconnect() d1.send 'bar' d1.disconnect() d2.send 456 d2.disconnect() , 10 describe 'without output ports', -> c = new noflo.Component c.inPorts.add 'foo' foo = noflo.internalSocket.createSocket() sig = noflo.internalSocket.createSocket() c.inPorts.foo.attach foo noflo.helpers.WirePattern c, in: 'foo' out: [] async: true , (foo, grp, out, callback) -> setTimeout -> sig.send foo callback() , 20 it 'should be fine still', (done) -> sig.on 'data', (data) -> chai.expect(data).to.equal 'foo' done() foo.send 'foo' foo.disconnect() describe 'when data processing is not possible at the moment', -> c = new noflo.Component c.inPorts.add 'line', datatype: 'string' .add 'repeat', datatype: 'int' .add 'when', datatype: 'string' default: 'later' c.outPorts.add 'res', datatype: 'string' .add 'error', datatype: 'object' line = noflo.internalSocket.createSocket() rpt = noflo.internalSocket.createSocket() whn = noflo.internalSocket.createSocket() res = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.line.attach line c.inPorts.repeat.attach rpt c.inPorts.when.attach whn c.outPorts.res.attach res c.outPorts.error.attach err c.invCount = 0 tryAgain = null noflo.helpers.WirePattern c, in: ['line', 'repeat'] params: 'when' out: 'res' async: true , (input, groups, out, completed, postpone, resume) -> this.invCount++ return if this.invCount > 100 # avoid deadlocks just in case switch this.params.when when 'now' repeated = '' repeated += input.line for i in [0...input.repeat] out.send repeated completed() when 'later' postpone() when 'afterTimeout' postpone false this.params.when = 'now' # don't recurse forever setTimeout -> resume() , 10 when 'whenItell' postpone false this.params.when = 'now' # don't recurse forever tryAgain = resume it 'should be able to postpone it until next tuple of data', (done) -> res.once 'data', (data) -> chai.expect(data).to.equal 'opopopopopopopopopop' chai.expect(c.invCount).to.equal 2 res.once 'data', (data) -> chai.expect(data).to.equal 'gogogo' chai.expect(c.invCount).to.equal 3 done() c.sendDefaults() line.send 'op' rpt.send 10 line.disconnect() rpt.disconnect() # no output expected at this point whn.send 'now' whn.disconnect() line.send 'go' rpt.send 3 line.disconnect() rpt.disconnect() # this flushes the earlier stuff it 'should be able to postpone and retry after timeout', (done) -> c.invCount = 0 res.once 'data', (data) -> chai.expect(data).to.equal 'dododo' chai.expect(c.invCount).to.equal 2 done() whn.send 'afterTimeout' whn.disconnect() line.send 'do' rpt.send 3 line.disconnect() rpt.disconnect() it 'should be able to postpone it and resume when needed', (done) -> c.invCount = 0 res.once 'data', (data) -> chai.expect(data).to.equal 'yoyo' chai.expect(c.invCount).to.equal 2 done() whn.send 'whenItell' whn.disconnect() line.send 'yo' rpt.send 2 line.disconnect() rpt.disconnect() # Here tryAgain got the resume callback setTimeout -> tryAgain() , 30 describe 'with many inputs and groups', -> c = new noflo.Component c.token = null c.inPorts.add 'in', datatype: 'string' .add 'message', datatype: 'string' .add 'repository', datatype: 'string' .add 'path', datatype: 'string' .add 'token', datatype: 'string', (event, payload) -> c.token = payload if event is 'data' c.outPorts.add 'out', datatype: 'string' .add 'error', datatype: 'object' noflo.helpers.WirePattern c, in: ['in', 'message', 'repository', 'path'] out: 'out' async: true forwardGroups: true , (data, groups, out, callback) -> setTimeout -> out.beginGroup data.path out.send data.message out.endGroup() do callback , 300 ins = noflo.internalSocket.createSocket() msg = noflo.internalSocket.createSocket() rep = noflo.internalSocket.createSocket() pth = noflo.internalSocket.createSocket() tkn = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.in.attach ins c.inPorts.message.attach msg c.inPorts.repository.attach rep c.inPorts.path.attach pth c.inPorts.token.attach tkn c.outPorts.out.attach out c.outPorts.error.attach err it 'should handle mixed flow well', (done) -> groups = [] refGroups = [ 'foo' 'http://techcrunch.com/2013/03/26/embedly-now/' 'path data' ] ends = 0 packets = [] refData = ['message data'] out.on 'begingroup', (grp) -> groups.push grp out.on 'endgroup', -> ends++ out.on 'data', (data) -> packets.push data out.on 'disconnect', -> chai.expect(groups).to.deep.equal refGroups chai.expect(ends).to.equal 3 chai.expect(packets).to.deep.equal refData done() err.on 'data', (data) -> done data rep.beginGroup 'foo' rep.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' rep.send 'repo data' rep.endGroup() rep.endGroup() ins.beginGroup 'foo' ins.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' ins.send 'ins data' msg.beginGroup 'foo' msg.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' msg.send 'message data' msg.endGroup() msg.endGroup() ins.endGroup() ins.endGroup() ins.disconnect() msg.disconnect() pth.beginGroup 'foo' pth.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' pth.send 'path data' pth.endGroup() pth.endGroup() pth.disconnect() rep.disconnect() describe 'for batch processing', -> # Component constructors newGenerator = (name) -> generator = new noflo.Component generator.inPorts.add 'count', datatype: 'int' generator.outPorts.add 'seq', datatype: 'int' noflo.helpers.WirePattern generator, in: 'count' out: 'seq' async: true forwardGroups: true ordered: true , (count, groups, seq, callback) -> sentCount = 0 for i in [1..count] do (i) -> delay = if i > 10 then i % 10 else i setTimeout -> seq.send i sentCount++ if sentCount is count callback() , delay newDoubler = (name) -> doubler = new noflo.Component doubler.inPorts.add 'num', datatype: 'int' doubler.outPorts.add 'out', datatype: 'int' noflo.helpers.WirePattern doubler, in: 'num' out: 'out' forwardGroups: true , (num, groups, out) -> dbl = 2*num out.send dbl newAdder = -> adder = new noflo.Component adder.inPorts.add 'num1', datatype: 'int' adder.inPorts.add 'num2', datatype: 'int' adder.outPorts.add 'sum', datatype: 'int' noflo.helpers.WirePattern adder, in: ['num1', 'num2'] out: 'sum' forwardGroups: true async: true ordered: true , (args, groups, out, callback) -> sum = args.num1 + args.num2 # out.send sum setTimeout -> out.send sum callback() , sum % 10 newSeqsum = -> seqsum = new noflo.Component seqsum.sum = 0 seqsum.inPorts.add 'seq', datatype: 'int', (event, payload) -> switch event when 'data' seqsum.sum += payload when 'disconnect' seqsum.outPorts.sum.send seqsum.sum seqsum.sum = 0 seqsum.outPorts.sum.disconnect() seqsum.outPorts.add 'sum', datatype: 'int' return seqsum # Wires genA = newGenerator 'A' genB = newGenerator 'B' dblA = newDoubler 'A' dblB = newDoubler 'B' addr = newAdder() sumr = newSeqsum() cntA = noflo.internalSocket.createSocket() cntB = noflo.internalSocket.createSocket() gen2dblA = noflo.internalSocket.createSocket() gen2dblB = noflo.internalSocket.createSocket() dblA2add = noflo.internalSocket.createSocket() dblB2add = noflo.internalSocket.createSocket() addr2sum = noflo.internalSocket.createSocket() sum = noflo.internalSocket.createSocket() genA.inPorts.count.attach cntA genB.inPorts.count.attach cntB genA.outPorts.seq.attach gen2dblA genB.outPorts.seq.attach gen2dblB dblA.inPorts.num.attach gen2dblA dblB.inPorts.num.attach gen2dblB dblA.outPorts.out.attach dblA2add dblB.outPorts.out.attach dblB2add addr.inPorts.num1.attach dblA2add addr.inPorts.num2.attach dblB2add addr.outPorts.sum.attach addr2sum sumr.inPorts.seq.attach addr2sum sumr.outPorts.sum.attach sum it 'should process sequences of packets separated by disconnects', (done) -> expected = [ 24, 40 ] actual = [] sum.on 'data', (data) -> actual.push data sum.on 'disconnect', -> chai.expect(actual).to.have.length.above 0 chai.expect(expected).to.have.length.above 0 act = actual.shift() exp = expected.shift() chai.expect(act).to.equal exp done() if expected.length is 0 cntA.send 3 cntA.disconnect() cntB.send 3 cntB.disconnect() cntA.send 4 cntB.send 4 cntA.disconnect() cntB.disconnect() describe 'for batch processing with groups', -> c1 = new noflo.Component c1.inPorts.add 'count', datatype: 'int' c1.outPorts.add 'seq', datatype: 'int' c2 = new noflo.Component c2.inPorts.add 'num', datatype: 'int' c2.outPorts.add 'out', datatype: 'int' cnt = noflo.internalSocket.createSocket() c1c2 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c1.inPorts.count.attach cnt c1.outPorts.seq.attach c1c2 c2.inPorts.num.attach c1c2 c2.outPorts.out.attach out it 'should wrap entire sequence with groups', (done) -> noflo.helpers.WirePattern c1, in: 'count' out: 'seq' async: true forwardGroups: true , (count, groups, out, callback) -> for i in [0...count] do (i) -> setTimeout -> out.send i , 0 setTimeout -> callback() , 3 noflo.helpers.WirePattern c2, in: 'num' out: 'out' forwardGroups: true , (num, groups, out) -> chai.expect(groups).to.deep.equal ['foo', 'bar'] out.send num expected = ['<foo>', '<bar>', 0, 1, 2, '</bar>', '</foo>'] actual = [] out.on 'begingroup', (grp) -> actual.push "<#{grp}>" out.on 'endgroup', (grp) -> actual.push "</#{grp}>" out.on 'data', (data) -> actual.push data out.on 'disconnect', -> chai.expect(actual).to.deep.equal expected done() cnt.beginGroup 'foo' cnt.beginGroup 'bar' cnt.send 3 cnt.endGroup() cnt.endGroup() cnt.disconnect() describe 'with addressable ports', -> c = new noflo.Component c.inPorts.add 'p1', datatype: 'int' addressable: true required: true .add 'd1', datatype: 'int' addressable: true .add 'd2', datatype: 'string' c.outPorts.add 'out', datatype: 'object' .add 'error', datatype: 'object' p11 = noflo.internalSocket.createSocket() p12 = noflo.internalSocket.createSocket() p13 = noflo.internalSocket.createSocket() d11 = noflo.internalSocket.createSocket() d12 = noflo.internalSocket.createSocket() d13 = noflo.internalSocket.createSocket() d2 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.p1.attach p11 c.inPorts.p1.attach p12 c.inPorts.p1.attach p13 c.inPorts.d1.attach d11 c.inPorts.d1.attach d12 c.inPorts.d1.attach d13 c.inPorts.d2.attach d2 c.outPorts.out.attach out c.outPorts.error.attach err it 'should wait for all param and any data port values (default)', (done) -> noflo.helpers.WirePattern c, in: ['d1', 'd2'] params: 'p1' out: 'out' arrayPolicy: # default values in: 'any' params: 'all' , (input, groups, out) -> chai.expect(c.params.p1).to.deep.equal { 0: 1, 1: 2, 2: 3 } chai.expect(input.d1).to.deep.equal {0: 1} chai.expect(input.d2).to.equal 'foo' done() d2.send 'foo' d2.disconnect() d11.send 1 d11.disconnect() p11.send 1 p11.disconnect() p12.send 2 p12.disconnect() p13.send 3 p13.disconnect() it 'should wait for any param and all data values', (done) -> noflo.helpers.WirePattern c, in: ['d1', 'd2'] params: 'p1' out: 'out' arrayPolicy: # inversed in: 'all' params: 'any' , (input, groups, out) -> chai.expect(c.params.p1).to.deep.equal {0: 1} chai.expect(input.d1).to.deep.equal { 0: 1, 1: 2, 2: 3 } chai.expect(input.d2).to.equal 'foo' done() out.on 'disconnect', -> console.log 'disc' d2.send 'foo' d2.disconnect() p11.send 1 p11.disconnect() d11.send 1 d11.disconnect() d12.send 2 d12.disconnect() d13.send 3 d13.disconnect() p12.send 2 p12.disconnect() p13.send 3 p13.disconnect() it 'should wait for all indexes of a single input', (done) -> noflo.helpers.WirePattern c, in: 'd1' out: 'out' arrayPolicy: in: 'all' , (input, groups, out) -> chai.expect(input).to.deep.equal { 0: 1, 1: 2, 2: 3 } done() d11.send 1 d11.disconnect() d12.send 2 d12.disconnect() d13.send 3 d13.disconnect() it 'should behave normally with string output from another component', (done) -> c = new noflo.Component c.inPorts.add 'd1', datatype: 'string' addressable: true c.outPorts.add 'out', datatype: 'object' d11 = noflo.internalSocket.createSocket() d12 = noflo.internalSocket.createSocket() d13 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.d1.attach d11 c.inPorts.d1.attach d12 c.inPorts.d1.attach d13 c.outPorts.out.attach out c2 = new noflo.Component c2.inPorts.add 'in', datatype: 'string' c2.outPorts.add 'out', datatype: 'string' noflo.helpers.WirePattern c2, in: 'in' out: 'out' forwardGroups: true , (input, groups, out) -> out.send input d3 = noflo.internalSocket.createSocket() c2.inPorts.in.attach d3 c2.outPorts.out.attach d11 noflo.helpers.WirePattern c, in: 'd1' out: 'out' , (input, groups, out) -> chai.expect(input).to.deep.equal {0: 'My string'} done() d3.send 'My string' d3.disconnect() describe 'when grouping requests', -> c = new noflo.Component c.inPorts.add 'x', datatype: 'int' .add 'y', datatype: 'int' c.outPorts.add 'out', datatype: 'object' x = noflo.internalSocket.createSocket() y = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.outPorts.out.attach out getUuid = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c is 'x' then r else r&0x3|0x8 v.toString 16 isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i generateRequests = (num) -> reqs = {} for i in [1..num] req = id: getUuid() num: i if i % 3 is 0 req.x = i else if i % 7 is 0 req.y = i else req.x = i req.y = 2*i reqs[req.id] = req reqs sendRequests = (reqs, delay) -> for id, req of reqs do (req) -> setTimeout -> if 'x' of req x.beginGroup req.id x.beginGroup 'x' x.beginGroup req.num x.send req.x x.endGroup() x.endGroup() x.endGroup() x.disconnect() if 'y' of req y.beginGroup req.id y.beginGroup 'y' y.beginGroup req.num y.send req.y y.endGroup() y.endGroup() y.endGroup() y.disconnect() , delay*req.num noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'out' async: true forwardGroups: true group: isUuid gcFrequency: 2 # every 2 requests gcTimeout: 0.02 # older than 20ms , (input, groups, out, done) -> setTimeout -> out.send id: groups[0] x: input.x y: input.y done() , 3 it 'should group requests by outer UUID group', (done) -> reqs = generateRequests 10 count = 0 out.on 'data', (data) -> count++ chai.expect(data.x).to.equal reqs[data.id].x chai.expect(data.y).to.equal reqs[data.id].y done() if count is 6 # 6 complete requests processed sendRequests reqs, 10 it 'should collect garbage every N requests', (done) -> # GC dropped 3 timed out packets, 1 should be left chai.expect(Object.keys(c._wpData[null].groupedData)).to.have.lengthOf 1 chai.expect(Object.keys(c._wpData[null].groupedGroups)).to.have.lengthOf 1 chai.expect(Object.keys(c._wpData[null].disconnectData)).to.have.lengthOf 1 done() it 'should be able to drop a request explicitly', (done) -> for key in Object.keys(c._wpData[null].groupedData) c.dropRequest null, key chai.expect(c._wpData[null].groupedData).to.deep.equal {} chai.expect(c._wpData[null].groupedGroups).to.deep.equal {} chai.expect(c._wpData[null].disconnectData).to.deep.equal {} done() describe 'when using scopes', -> c = new noflo.Component inPorts: x: datatype: 'int' y: datatype: 'int' outPorts: out: datatype: 'object' x = noflo.internalSocket.createSocket() y = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.outPorts.out.attach out getUuid = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c is 'x' then r else r&0x3|0x8 v.toString 16 isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i generateRequests = (num) -> reqs = {} for i in [1..num] req = id: getUuid() num: i if i % 3 is 0 req.x = i else if i % 7 is 0 req.y = i else req.x = i req.y = 2*i reqs[req.id] = req reqs sendRequests = (reqs, delay) -> for id, req of reqs do (req) -> setTimeout -> if 'x' of req x.post new noflo.IP 'openBracket', 'x', scope: req.id x.post new noflo.IP 'data', req.x, scope: req.id x.post new noflo.IP 'closeBracket', null, scope: req.id x.disconnect() if 'y' of req y.post new noflo.IP 'openBracket', 'y', scope: req.id y.post new noflo.IP 'data', req.y, scope: req.id y.post new noflo.IP 'closeBracket', null, scope: req.id y.disconnect() , delay*req.num noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'out' async: true forwardGroups: true , (input, groups, out, done, postpone, resume, scope) -> setTimeout -> out.send id: scope x: input.x y: input.y done() , 3 it 'should scope requests by proper UUID', (done) -> reqs = generateRequests 10 count = 0 out.on 'data', (data) -> count++ chai.expect(data.x).to.equal reqs[data.id].x chai.expect(data.y).to.equal reqs[data.id].y done() if count is 6 # 6 complete requests processed sendRequests reqs, 10 describe 'MultiError', -> describe 'with simple sync processes', -> c = new noflo.Component c.inPorts.add 'form', datatype: 'object' handle: (ip) -> return unless ip.type is 'data' payload = ip.data # Validate form unless payload.name and payload.name.match /^\w{3,16}$/ c.error noflo.helpers.CustomError 'Incorrect name', kind: 'form_error' code: 'invalid_name' param: 'name' unless payload.email and payload.email.match /^\w+@\w+\.\w+$/ c.error noflo.helpers.CustomError 'Incorrect email', kind: 'form_error' code: 'invalid_email' param: 'email' unless payload.accept c.error noflo.helpers.CustomError 'Terms have to be accepted', kind: 'form_error' code: 'terms_not_accepted' param: 'accept' # Finish validation return c.fail() if c.hasErrors # Emulating some processing logic here if payload.name is 'DelayLama' # oops c.outPorts.saved.send false c.outPorts.saved.disconnect() return c.fail noflo.helpers.CustomError 'Suspended for a meditation', kind: 'runtime_error' code: 'delay_lama_detected' else c.outPorts.saved.send true c.outPorts.saved.disconnect() c.outPorts.add 'saved', datatype: 'boolean' c.outPorts.add 'error', datatype: 'object' form = new noflo.internalSocket.createSocket() saved = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.form.attach form c.outPorts.saved.attach saved c.outPorts.error.attach err noflo.helpers.MultiError c it 'should support multiple customized error messages', (done) -> errCount = 0 err.on 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'form_error' errCount++ err.on 'disconnect', -> chai.expect(errCount).to.equal 3 done() form.send name: 'Bo' email: 'missing' form.disconnect() it 'should pass if everything is correct', (done) -> hadData = false saved.removeAllListeners() saved.once 'data', (data) -> chai.expect(data).to.be.true hadData = true saved.once 'disconnect', -> chai.expect(hadData).to.be.true done() err.removeAllListeners() err.on 'data', (data) -> done data form.send name: 'Josh' email: 'josh@example.com' accept: true form.disconnect() it 'should handle fatals and runtimes normally', (done) -> saved.once 'data', (data) -> chai.expect(data).to.be.false err.removeAllListeners() errCount = 0 err.once 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'runtime_error' errCount++ err.once 'disconnect', -> chai.expect(errCount).to.equal 1 done() form.send name: 'DelayLama' email: 'delay@lama.ti' accept: true form.disconnect() describe 'with async processes and groups', -> c = new noflo.Component c.inPorts.add 'form', datatype: 'object' c.outPorts.add 'saved', datatype: 'boolean' c.outPorts.add 'error', datatype: 'object' form = new noflo.internalSocket.createSocket() saved = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.form.attach form c.outPorts.saved.attach saved c.outPorts.error.attach err noflo.helpers.WirePattern c, in: 'form' out: 'saved' async: true forwardGroups: true name: 'Registration' , (payload, groups, out, callback) -> # Validate form unless payload.name and payload.name.match /^\w{3,16}$/ this.error noflo.helpers.CustomError('Incorrect name', kind: 'form_error' code: 'invalid_name' param: 'name' ), ['e1'] unless payload.email and payload.email.match /^\w+@\w+\.\w+$/ this.error noflo.helpers.CustomError('Incorrect email', kind: 'form_error' code: 'invalid_email' param: 'email' ), ['e2'] unless payload.accept this.error noflo.helpers.CustomError('Terms have to be accepted', kind: 'form_error' code: 'terms_not_accepted' param: 'accept' ), ['e3'] # Finish validation return callback no if this.hasErrors setTimeout -> # Emulating some processing logic here if payload.name is 'DelayLama' # oops out.send false return callback noflo.helpers.CustomError 'Suspended for a meditation', kind: 'runtime_error' code: 'delay_lama_detected' else out.send true callback() , 10 it 'should support multiple error messages and groups and scope', (done) -> expected = [ 'Registration' 'async0' 'e1' 'async0' 'e2' 'async0' 'e3' ] actual = [] errCount = 0 brackets = 0 err.on 'ip', (ip) -> chai.expect(ip.scope).to.equal 'foo' if ip.type is 'openBracket' brackets++ return actual.push ip.data if ip.type is 'data' data = ip.data chai.expect(data).to.be.an.error chai.expect(data.kind).to.equal 'form_error' errCount++ if ip.type is 'closeBracket' brackets-- if brackets is 0 chai.expect(errCount).to.equal 3 chai.expect(actual).to.deep.equal expected done() form.post new noflo.IP 'openBracket', 'async0', scope: 'foo' form.post new noflo.IP 'data', name: 'Bo' email: 'missing' , scope: 'foo' form.post new noflo.IP 'closeBracket', 'async0', scope: 'foo' # form.disconnect() it 'should pass if everything is correct', (done) -> hadData = false saved.removeAllListeners() saved.once 'data', (data) -> chai.expect(data).to.be.true hadData = true saved.once 'disconnect', -> chai.expect(hadData).to.be.true done() err.removeAllListeners() err.on 'data', (data) -> done data form.send name: 'Josh' email: 'josh@example.com' accept: true form.disconnect() it 'should handle fatals and runtimes normally', (done) -> saved.once 'data', (data) -> chai.expect(data).to.be.false err.removeAllListeners() errCount = 0 grpCount = 0 err.on 'begingroup', (grp) -> chai.expect(grp).to.equal 'Registration' grpCount++ err.once 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'runtime_error' errCount++ err.once 'disconnect', -> chai.expect(errCount).to.equal 1 chai.expect(grpCount).to.equal 1 done() form.send name: 'DelayLama' email: 'delay@lama.ti' accept: true form.disconnect() it 'should reset state if component is shut down', (done) -> c2 = new noflo.Component c2.inPorts.add 'name', datatype: 'string' handle: (ip) -> return unless ip.type is 'data' c2.error new Error "The name will never pass!" noflo.helpers.MultiError c2 ins = new noflo.internalSocket.createSocket() c2.inPorts.name.attach ins ins.send 'Norman' chai.expect(c2.hasErrors).to.be.true chai.expect(c2.errors).to.be.an 'array' chai.expect(c2.errors).to.have.lengthOf 1 c2.shutdown() chai.expect(c2.hasErrors).to.be.false chai.expect(c2.errors).to.be.an 'array' chai.expect(c2.errors).to.have.lengthOf 0 done()
153661
if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/ chai = require 'chai' unless chai noflo = require '../src/lib/NoFlo.coffee' else noflo = require 'noflo' describe 'Component traits', -> describe 'MapComponent', -> c = null it 'should pass data to the callback', -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data) -> chai.expect(data).to.equal 1 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s.send 1 it 'should pass groups to the callback', -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data, groups) -> chai.expect(groups).to.eql [ 'one' 'two' ] chai.expect(data).to.equal 1 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s.beginGroup 'one' s.beginGroup 'two' s.send 1 it 'should send groups and disconnect through', (done) -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data, groups, out) -> out.send data * 2 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s2 = new noflo.internalSocket.createSocket() c.outPorts.out.attach s2 groups = [] s2.on 'begingroup', (group) -> groups.push group s2.on 'data', (data) -> chai.expect(groups.length).to.equal 2 chai.expect(data).to.equal 6 s2.on 'endgroup', -> groups.pop() s2.on 'disconnect', -> chai.expect(groups.length).to.equal 0 done() s.beginGroup 'one' s.beginGroup 'two' s.send 3 s.endGroup() s.endGroup() s.disconnect() describe 'WirePattern', -> describe 'when grouping by packet groups', -> c = null x = null y = null z = null p = null before (done) -> c = new noflo.Component c.inPorts.add 'x', required: true datatype: 'int' .add 'y', required: true datatype: 'int' .add 'z', required: true datatype: 'int' c.outPorts.add 'point' x = new noflo.internalSocket.createSocket() y = new noflo.internalSocket.createSocket() z = new noflo.internalSocket.createSocket() p = new noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.inPorts.z.attach z c.outPorts.point.attach p done() it 'should pass data and groups to the callback', (done) -> src = 111: {x: 1, y: 2, z: 3} 222: {x: 4, y: 5, z: 6} 333: {x: 7, y: 8, z: 9} noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' group: true forwardGroups: true , (data, groups, out) -> chai.expect(groups.length).to.be.above 0 chai.expect(data).to.deep.equal src[groups[0]] out.send data groups = [] count = 0 p.on 'begingroup', (grp) -> groups.push grp p.on 'endgroup', -> groups.pop() p.on 'data', (data) -> count++ p.on 'disconnect', -> done() if count is 3 and groups.length is 0 for key, grp of src x.beginGroup key y.beginGroup key z.beginGroup key x.send grp.x y.send grp.y z.send grp.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should work without a group provided', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' , (data, groups, out) -> chai.expect(groups.length).to.equal 0 out.send {x: data.x, y: data.y, z: data.z} p.once 'data', (data) -> chai.expect(data).to.deep.equal {x: 123, y: 456, z: 789} done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() it 'should process inputs for different groups independently with group: true', (done) -> src = 1: {x: 1, y: 2, z: 3} 2: {x: 4, y: 5, z: 6} 3: {x: 7, y: 8, z: 9} inOrder = [ [ 1, 'x' ] [ 3, 'z' ] [ 2, 'y' ] [ 2, 'x' ] [ 1, 'z' ] [ 2, 'z' ] [ 3, 'x' ] [ 1, 'y' ] [ 3, 'y' ] ] outOrder = [ 2, 1, 3 ] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' group: true forwardGroups: true , (data, groups, out) -> out.send {x: data.x, y: data.y, z: data.z} groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'endgroup', (grp) -> groups.pop() p.on 'data', (data) -> chai.expect(groups.length).to.equal 1 chai.expect(groups[0]).to.equal outOrder[0] chai.expect(data).to.deep.equal src[outOrder[0]] outOrder.shift() done() unless outOrder.length for tuple in inOrder input = null switch tuple[1] when 'x' input = x when 'y' input = y when 'z' input = z input.beginGroup tuple[0] input.send src[tuple[0]][tuple[1]] input.endGroup() input.disconnect() it 'should support asynchronous handlers', (done) -> point = x: 123 y: 456 z: 789 noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' async: true group: true forwardGroups: true , (data, groups, out, callback) -> setTimeout -> out.send {x: data.x, y: data.y, z: data.z} callback() , 100 p.removeAllListeners() counter = 0 hadData = false p.on 'begingroup', (grp) -> counter++ p.on 'endgroup', -> counter-- p.once 'data', (data) -> chai.expect(data).to.deep.equal point hadData = true p.once 'disconnect', -> chai.expect(counter).to.equal 0 chai.expect(hadData).to.be.true done() x.beginGroup 'async' y.beginGroup 'async' z.beginGroup 'async' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should not forward groups if forwarding is off', (done) -> point = x: 123 y: 456 noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'point' , (data, groups, out) -> out.send { x: data.x, y: data.y } p.removeAllListeners() counter = 0 hadData = false p.on 'begingroup', (grp) -> counter++ p.on 'data', (data) -> chai.expect(data).to.deep.equal point hadData = true p.once 'disconnect', -> chai.expect(counter).to.equal 0 chai.expect(hadData).to.be.true done() x.beginGroup 'doNotForwardMe' y.beginGroup 'doNotForwardMe' x.send point.x y.send point.y x.endGroup() y.endGroup() x.disconnect() y.disconnect() it 'should forward groups from a specific port only', (done) -> point = x: 123 y: 456 z: 789 refGroups = ['boo'] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' forwardGroups: 'y' , (data, groups, out) -> out.send { x: data.x, y: data.y, z: data.z } p.removeAllListeners() groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'data', (data) -> chai.expect(data).to.deep.equal point p.once 'disconnect', -> chai.expect(groups).to.deep.equal refGroups done() x.beginGroup 'foo' y.beginGroup 'boo' z.beginGroup 'bar' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should forward groups from selected ports only', (done) -> point = x: 123 y: 456 z: 789 refGroups = ['foo', 'bar'] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' forwardGroups: [ 'x', 'z' ] , (data, groups, out) -> out.send { x: data.x, y: data.y, z: data.z } p.removeAllListeners() groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'data', (data) -> chai.expect(data).to.deep.equal point p.once 'disconnect', -> chai.expect(groups).to.deep.equal refGroups done() x.beginGroup 'foo' y.beginGroup 'boo' z.beginGroup 'bar' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() describe 'when `this` context is important', -> c = new noflo.Component c.inPorts.add 'x', required: true datatype: 'int' .add 'y', required: true datatype: 'int' .add 'z', required: true datatype: 'int' c.outPorts.add 'point' x = new noflo.internalSocket.createSocket() y = new noflo.internalSocket.createSocket() z = new noflo.internalSocket.createSocket() p = new noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.inPorts.z.attach z c.outPorts.point.attach p it 'should correctly bind component to `this` context', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' , (data, groups, out) -> chai.expect(this).to.deep.equal c out.send {x: data.x, y: data.y, z: data.z} p.once 'data', (data) -> chai.expect(data).to.deep.equal {x: 123, y: 456, z: 789} done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() it 'should correctly bind component to `this` context in async mode', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] async: true out: 'point' , (data, groups, out, callback) -> chai.expect(this).to.deep.equal c out.send {x: data.x, y: data.y, z: data.z} callback() p.once 'data', (data) -> done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() describe 'when in async mode and packet order matters', -> c = new noflo.Component c.inPorts.add 'delay', datatype: 'int' .add 'msg', datatype: 'string' c.outPorts.add 'out', datatype: 'object' .add 'load', datatype: 'int' delay = new noflo.internalSocket.createSocket() msg = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() load = new noflo.internalSocket.createSocket() c.inPorts.delay.attach delay c.inPorts.msg.attach msg c.outPorts.out.attach out c.outPorts.load.attach load it 'should preserve input order at the output', (done) -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false , (data, groups, res, callback) -> setTimeout -> res.send { delay: data.delay, msg: data.msg } callback() , data.delay sample = [ { delay: 30, msg: "one" } { delay: 0, msg: "two" } { delay: 20, msg: "three" } { delay: 10, msg: "four" } ] out.on 'data', (data) -> chai.expect(data).to.deep.equal sample.shift() out.on 'disconnect', -> done() if sample.length is 0 expected = [1, 2, 3, 4, 3, 2, 1, 0] load.on 'data', (data) -> chai.expect(data).to.equal expected.shift() idx = 0 for ip in sample delay.beginGroup idx delay.send ip.delay delay.endGroup() msg.beginGroup idx msg.send ip.msg msg.endGroup() delay.disconnect() msg.disconnect() idx++ it 'should throw if receiveStreams is used', (done) -> f = -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false receiveStreams: ['delay', 'msg'] , (data, groups, res, callback) -> callback() chai.expect(f).to.throw Error done() it 'should throw if sendStreams is used', (done) -> f = -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false sendStreams: ['out'] , (data, groups, res, callback) -> callback() chai.expect(f).to.throw Error done() # it 'should support complex substreams', (done) -> # out.removeAllListeners() # load.removeAllListeners() # c.cntr = 0 # helpers.WirePattern c, # in: ['delay', 'msg'] # async: true # ordered: true # group: false # receiveStreams: ['delay', 'msg'] # , (data, groups, res, callback) -> # # Substream to object conversion validation # # (the hard way) # chai.expect(data.delay instanceof Substream).to.be.true # chai.expect(data.msg instanceof Substream).to.be.true # delayObj = data.delay.toObject() # msgObj = data.msg.toObject() # index0 = this.cntr.toString() # chai.expect(Object.keys(delayObj)[0]).to.equal index0 # chai.expect(Object.keys(msgObj)[0]).to.equal index0 # subDelay = delayObj[index0] # subMsg = msgObj[index0] # index1 = (10 + this.cntr).toString() # chai.expect(Object.keys(subDelay)[0]).to.equal index1 # chai.expect(Object.keys(subMsg)[0]).to.equal index1 # delayData = subDelay[index1] # msgData = subMsg[index1] # chai.expect(delayData).to.equal sample[c.cntr].delay # chai.expect(msgData).to.equal sample[c.cntr].msg # this.cntr++ # setTimeout -> # # Substream tree traversal (the easy way) # for k0, v0 of msgObj # res.beginGroup k0 # res.send k0 # for k1, v1 of v0 # res.beginGroup k1 # res.send # delay: delayObj[k0][k1] # msg: msgObj[k0][k1] # res.endGroup() # res.send k1 # res.endGroup() # callback() # , data.delay # sample = [ # { delay: 30, msg: "one" } # { delay: 0, msg: "two" } # { delay: 20, msg: "three" } # { delay: 10, msg: "four" } # ] # expected = [ # '0', '0', '10', sample[0], '10' # '1', '1', '11', sample[1], '11' # '2', '2', '12', sample[2], '12' # '3', '3', '13', sample[3], '13' # ] # out.on 'begingroup', (grp) -> # chai.expect(grp).to.equal expected.shift() # out.on 'data', (data) -> # chai.expect(data).to.deep.equal expected.shift() # out.on 'disconnect', -> # done() if expected.length is 0 # for i in [0..3] # delay.beginGroup i # delay.beginGroup 10 + i # delay.send sample[i].delay # delay.endGroup() # delay.endGroup() # msg.beginGroup i # msg.beginGroup 10 + i # msg.send sample[i].msg # msg.endGroup() # msg.endGroup() # delay.disconnect() # msg.disconnect() describe 'when grouping by field', -> c = new noflo.Component c.inPorts.add 'user', datatype: 'object' .add 'message', datatype: 'object' c.outPorts.add 'signedmessage' usr = new noflo.internalSocket.createSocket() msg = new noflo.internalSocket.createSocket() umsg = new noflo.internalSocket.createSocket() c.inPorts.user.attach usr c.inPorts.message.attach msg c.outPorts.signedmessage.attach umsg it 'should match objects by specific field', (done) -> noflo.helpers.WirePattern c, in: ['user', 'message'] out: 'signedmessage' async: true field: 'request' , (data, groups, out, callback) -> setTimeout -> out.send request: data.request user: data.user.name text: data.message.text callback() , 10 users = 14: {request: 14, id: 21, name: '<NAME>'} 12: {request: 12, id: 25, name: '<NAME>'} 34: {request: 34, id: 84, name: '<NAME>'} messages = 34: {request: 34, id: 234, text: 'Hello world'} 12: {request: 12, id: 82, text: 'Aloha amigos'} 14: {request: 14, id: 249, text: 'Node.js ftw'} counter = 0 umsg.on 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.request).to.be.ok chai.expect(data.user).to.equal users[data.request].name chai.expect(data.text).to.equal messages[data.request].text counter++ done() if counter is 3 # Send input asynchronously with mixed delays for req, user of users do (req, user) -> setTimeout -> usr.send user usr.disconnect() , req for req, mesg of messages do (req, mesg) -> setTimeout -> msg.send mesg msg.disconnect() , req describe 'when there are multiple output routes', -> c = new noflo.Component c.inPorts.add 'num', datatype: 'int' .add 'str', datatype: 'string' c.outPorts.add 'odd', datatype: 'object' .add 'even', datatype: 'object' num = new noflo.internalSocket.createSocket() str = new noflo.internalSocket.createSocket() odd = new noflo.internalSocket.createSocket() even = new noflo.internalSocket.createSocket() c.inPorts.num.attach num c.inPorts.str.attach str c.outPorts.odd.attach odd c.outPorts.even.attach even it 'should send output to one or more of them', (done) -> numbers = ['cero', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'] noflo.helpers.WirePattern c, in: ['num', 'str'] out: ['odd', 'even'] async: true ordered: true , (data, groups, outs, callback) -> setTimeout -> if data.num % 2 is 1 outs.odd.beginGroup grp for grp in groups outs.odd.send data outs.odd.endGroup() for grp in groups else outs.even.beginGroup grp for grp in groups outs.even.send data outs.even.endGroup() for grp in groups callback() , 0 grpCounter = 0 dataCounter = 0 odd.on 'begingroup', (grp) -> grpCounter++ odd.on 'data', (data) -> chai.expect(data.num % 2).to.equal 1 chai.expect(data.str).to.equal numbers[data.num] dataCounter++ odd.on 'disconnect', -> done() if dataCounter is 10 and grpCounter is 10 even.on 'begingroup', (grp) -> grpCounter++ even.on 'data', (data) -> chai.expect(data.num % 2).to.equal 0 chai.expect(data.str).to.equal numbers[data.num] dataCounter++ even.on 'disconnect', -> done() if dataCounter is 10 and grpCounter is 10 for i in [0...10] num.beginGroup i num.send i num.endGroup i num.disconnect() str.beginGroup i str.send numbers[i] str.endGroup i str.disconnect() describe 'when there are parameter ports', -> c = null p1 = p2 = p3 = d1 = d2 = out = err = 0 beforeEach -> c = new noflo.Component c.inPorts.add 'param1', datatype: 'string' required: true .add 'param2', datatype: 'int' required: false .add 'param3', datatype: 'int' required: true default: 0 .add 'data1', datatype: 'string' .add 'data2', datatype: 'int' c.outPorts.add 'out', datatype: 'object' .add 'error', datatype: 'object' p1 = new noflo.internalSocket.createSocket() p2 = new noflo.internalSocket.createSocket() p3 = new noflo.internalSocket.createSocket() d1 = new noflo.internalSocket.createSocket() d2 = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.param1.attach p1 c.inPorts.param2.attach p2 c.inPorts.param3.attach p3 c.inPorts.data1.attach d1 c.inPorts.data2.attach d2 c.outPorts.out.attach out c.outPorts.error.attach err it 'should wait for required params without default value', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.be.undefined chai.expect(data.p3).to.equal 0 chai.expect(data.d1).to.equal 'foo' chai.expect(data.d2).to.equal 123 # And later when second param arrives out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 568 chai.expect(data.p3).to.equal 800 chai.expect(data.d1).to.equal 'bar' chai.expect(data.d2).to.equal 456 done() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() c.sendDefaults() p1.send 'req' p1.disconnect() # the handler should be triggered here setTimeout -> p2.send 568 p2.disconnect() p3.send 800 p3.disconnect() d1.send 'bar' d1.disconnect() d2.send 456 d2.disconnect() , 10 it 'should work for async procs too', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> delay = if c.params.param2 then c.params.param2 else 10 setTimeout -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res , delay out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 56 chai.expect(data.p3).to.equal 0 chai.expect(data.d1).to.equal 'foo' chai.expect(data.d2).to.equal 123 done() p2.send 56 p2.disconnect() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() c.sendDefaults() p1.send 'req' p1.disconnect() # the handler should be triggered here it 'should reset state if shutdown() is called', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> out.send p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 d1.send 'boo' d1.disconnect() p2.send 73 p2.disconnect() chai.expect(Object.keys(c._wpData[null].groupedData)).to.have.length.above 0 chai.expect(Object.keys(c._wpData[null].params)).to.have.length.above 0 c.shutdown() chai.expect(c._wpData).to.deep.equal {} done() it 'should drop premature data if configured to do so', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] dropInput: true , (input, groups, out) -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 568 chai.expect(data.p3).to.equal 800 chai.expect(data.d1).to.equal 'bar' chai.expect(data.d2).to.equal 456 done() c.sendDefaults() p2.send 568 p2.disconnect() p3.send 800 p3.disconnect() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() # Data is dropped at this point setTimeout -> p1.send 'req' p1.disconnect() d1.send 'bar' d1.disconnect() d2.send 456 d2.disconnect() , 10 describe 'without output ports', -> c = new noflo.Component c.inPorts.add 'foo' foo = noflo.internalSocket.createSocket() sig = noflo.internalSocket.createSocket() c.inPorts.foo.attach foo noflo.helpers.WirePattern c, in: 'foo' out: [] async: true , (foo, grp, out, callback) -> setTimeout -> sig.send foo callback() , 20 it 'should be fine still', (done) -> sig.on 'data', (data) -> chai.expect(data).to.equal 'foo' done() foo.send 'foo' foo.disconnect() describe 'when data processing is not possible at the moment', -> c = new noflo.Component c.inPorts.add 'line', datatype: 'string' .add 'repeat', datatype: 'int' .add 'when', datatype: 'string' default: 'later' c.outPorts.add 'res', datatype: 'string' .add 'error', datatype: 'object' line = noflo.internalSocket.createSocket() rpt = noflo.internalSocket.createSocket() whn = noflo.internalSocket.createSocket() res = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.line.attach line c.inPorts.repeat.attach rpt c.inPorts.when.attach whn c.outPorts.res.attach res c.outPorts.error.attach err c.invCount = 0 tryAgain = null noflo.helpers.WirePattern c, in: ['line', 'repeat'] params: 'when' out: 'res' async: true , (input, groups, out, completed, postpone, resume) -> this.invCount++ return if this.invCount > 100 # avoid deadlocks just in case switch this.params.when when 'now' repeated = '' repeated += input.line for i in [0...input.repeat] out.send repeated completed() when 'later' postpone() when 'afterTimeout' postpone false this.params.when = 'now' # don't recurse forever setTimeout -> resume() , 10 when 'whenItell' postpone false this.params.when = 'now' # don't recurse forever tryAgain = resume it 'should be able to postpone it until next tuple of data', (done) -> res.once 'data', (data) -> chai.expect(data).to.equal 'opopopopopopopopopop' chai.expect(c.invCount).to.equal 2 res.once 'data', (data) -> chai.expect(data).to.equal 'gogogo' chai.expect(c.invCount).to.equal 3 done() c.sendDefaults() line.send 'op' rpt.send 10 line.disconnect() rpt.disconnect() # no output expected at this point whn.send 'now' whn.disconnect() line.send 'go' rpt.send 3 line.disconnect() rpt.disconnect() # this flushes the earlier stuff it 'should be able to postpone and retry after timeout', (done) -> c.invCount = 0 res.once 'data', (data) -> chai.expect(data).to.equal 'dododo' chai.expect(c.invCount).to.equal 2 done() whn.send 'afterTimeout' whn.disconnect() line.send 'do' rpt.send 3 line.disconnect() rpt.disconnect() it 'should be able to postpone it and resume when needed', (done) -> c.invCount = 0 res.once 'data', (data) -> chai.expect(data).to.equal 'yoyo' chai.expect(c.invCount).to.equal 2 done() whn.send 'whenItell' whn.disconnect() line.send 'yo' rpt.send 2 line.disconnect() rpt.disconnect() # Here tryAgain got the resume callback setTimeout -> tryAgain() , 30 describe 'with many inputs and groups', -> c = new noflo.Component c.token = null c.inPorts.add 'in', datatype: 'string' .add 'message', datatype: 'string' .add 'repository', datatype: 'string' .add 'path', datatype: 'string' .add 'token', datatype: 'string', (event, payload) -> c.token = payload if event is 'data' c.outPorts.add 'out', datatype: 'string' .add 'error', datatype: 'object' noflo.helpers.WirePattern c, in: ['in', 'message', 'repository', 'path'] out: 'out' async: true forwardGroups: true , (data, groups, out, callback) -> setTimeout -> out.beginGroup data.path out.send data.message out.endGroup() do callback , 300 ins = noflo.internalSocket.createSocket() msg = noflo.internalSocket.createSocket() rep = noflo.internalSocket.createSocket() pth = noflo.internalSocket.createSocket() tkn = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.in.attach ins c.inPorts.message.attach msg c.inPorts.repository.attach rep c.inPorts.path.attach pth c.inPorts.token.attach tkn c.outPorts.out.attach out c.outPorts.error.attach err it 'should handle mixed flow well', (done) -> groups = [] refGroups = [ 'foo' 'http://techcrunch.com/2013/03/26/embedly-now/' 'path data' ] ends = 0 packets = [] refData = ['message data'] out.on 'begingroup', (grp) -> groups.push grp out.on 'endgroup', -> ends++ out.on 'data', (data) -> packets.push data out.on 'disconnect', -> chai.expect(groups).to.deep.equal refGroups chai.expect(ends).to.equal 3 chai.expect(packets).to.deep.equal refData done() err.on 'data', (data) -> done data rep.beginGroup 'foo' rep.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' rep.send 'repo data' rep.endGroup() rep.endGroup() ins.beginGroup 'foo' ins.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' ins.send 'ins data' msg.beginGroup 'foo' msg.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' msg.send 'message data' msg.endGroup() msg.endGroup() ins.endGroup() ins.endGroup() ins.disconnect() msg.disconnect() pth.beginGroup 'foo' pth.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' pth.send 'path data' pth.endGroup() pth.endGroup() pth.disconnect() rep.disconnect() describe 'for batch processing', -> # Component constructors newGenerator = (name) -> generator = new noflo.Component generator.inPorts.add 'count', datatype: 'int' generator.outPorts.add 'seq', datatype: 'int' noflo.helpers.WirePattern generator, in: 'count' out: 'seq' async: true forwardGroups: true ordered: true , (count, groups, seq, callback) -> sentCount = 0 for i in [1..count] do (i) -> delay = if i > 10 then i % 10 else i setTimeout -> seq.send i sentCount++ if sentCount is count callback() , delay newDoubler = (name) -> doubler = new noflo.Component doubler.inPorts.add 'num', datatype: 'int' doubler.outPorts.add 'out', datatype: 'int' noflo.helpers.WirePattern doubler, in: 'num' out: 'out' forwardGroups: true , (num, groups, out) -> dbl = 2*num out.send dbl newAdder = -> adder = new noflo.Component adder.inPorts.add 'num1', datatype: 'int' adder.inPorts.add 'num2', datatype: 'int' adder.outPorts.add 'sum', datatype: 'int' noflo.helpers.WirePattern adder, in: ['num1', 'num2'] out: 'sum' forwardGroups: true async: true ordered: true , (args, groups, out, callback) -> sum = args.num1 + args.num2 # out.send sum setTimeout -> out.send sum callback() , sum % 10 newSeqsum = -> seqsum = new noflo.Component seqsum.sum = 0 seqsum.inPorts.add 'seq', datatype: 'int', (event, payload) -> switch event when 'data' seqsum.sum += payload when 'disconnect' seqsum.outPorts.sum.send seqsum.sum seqsum.sum = 0 seqsum.outPorts.sum.disconnect() seqsum.outPorts.add 'sum', datatype: 'int' return seqsum # Wires genA = newGenerator 'A' genB = newGenerator 'B' dblA = newDoubler 'A' dblB = newDoubler 'B' addr = newAdder() sumr = newSeqsum() cntA = noflo.internalSocket.createSocket() cntB = noflo.internalSocket.createSocket() gen2dblA = noflo.internalSocket.createSocket() gen2dblB = noflo.internalSocket.createSocket() dblA2add = noflo.internalSocket.createSocket() dblB2add = noflo.internalSocket.createSocket() addr2sum = noflo.internalSocket.createSocket() sum = noflo.internalSocket.createSocket() genA.inPorts.count.attach cntA genB.inPorts.count.attach cntB genA.outPorts.seq.attach gen2dblA genB.outPorts.seq.attach gen2dblB dblA.inPorts.num.attach gen2dblA dblB.inPorts.num.attach gen2dblB dblA.outPorts.out.attach dblA2add dblB.outPorts.out.attach dblB2add addr.inPorts.num1.attach dblA2add addr.inPorts.num2.attach dblB2add addr.outPorts.sum.attach addr2sum sumr.inPorts.seq.attach addr2sum sumr.outPorts.sum.attach sum it 'should process sequences of packets separated by disconnects', (done) -> expected = [ 24, 40 ] actual = [] sum.on 'data', (data) -> actual.push data sum.on 'disconnect', -> chai.expect(actual).to.have.length.above 0 chai.expect(expected).to.have.length.above 0 act = actual.shift() exp = expected.shift() chai.expect(act).to.equal exp done() if expected.length is 0 cntA.send 3 cntA.disconnect() cntB.send 3 cntB.disconnect() cntA.send 4 cntB.send 4 cntA.disconnect() cntB.disconnect() describe 'for batch processing with groups', -> c1 = new noflo.Component c1.inPorts.add 'count', datatype: 'int' c1.outPorts.add 'seq', datatype: 'int' c2 = new noflo.Component c2.inPorts.add 'num', datatype: 'int' c2.outPorts.add 'out', datatype: 'int' cnt = noflo.internalSocket.createSocket() c1c2 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c1.inPorts.count.attach cnt c1.outPorts.seq.attach c1c2 c2.inPorts.num.attach c1c2 c2.outPorts.out.attach out it 'should wrap entire sequence with groups', (done) -> noflo.helpers.WirePattern c1, in: 'count' out: 'seq' async: true forwardGroups: true , (count, groups, out, callback) -> for i in [0...count] do (i) -> setTimeout -> out.send i , 0 setTimeout -> callback() , 3 noflo.helpers.WirePattern c2, in: 'num' out: 'out' forwardGroups: true , (num, groups, out) -> chai.expect(groups).to.deep.equal ['foo', 'bar'] out.send num expected = ['<foo>', '<bar>', 0, 1, 2, '</bar>', '</foo>'] actual = [] out.on 'begingroup', (grp) -> actual.push "<#{grp}>" out.on 'endgroup', (grp) -> actual.push "</#{grp}>" out.on 'data', (data) -> actual.push data out.on 'disconnect', -> chai.expect(actual).to.deep.equal expected done() cnt.beginGroup 'foo' cnt.beginGroup 'bar' cnt.send 3 cnt.endGroup() cnt.endGroup() cnt.disconnect() describe 'with addressable ports', -> c = new noflo.Component c.inPorts.add 'p1', datatype: 'int' addressable: true required: true .add 'd1', datatype: 'int' addressable: true .add 'd2', datatype: 'string' c.outPorts.add 'out', datatype: 'object' .add 'error', datatype: 'object' p11 = noflo.internalSocket.createSocket() p12 = noflo.internalSocket.createSocket() p13 = noflo.internalSocket.createSocket() d11 = noflo.internalSocket.createSocket() d12 = noflo.internalSocket.createSocket() d13 = noflo.internalSocket.createSocket() d2 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.p1.attach p11 c.inPorts.p1.attach p12 c.inPorts.p1.attach p13 c.inPorts.d1.attach d11 c.inPorts.d1.attach d12 c.inPorts.d1.attach d13 c.inPorts.d2.attach d2 c.outPorts.out.attach out c.outPorts.error.attach err it 'should wait for all param and any data port values (default)', (done) -> noflo.helpers.WirePattern c, in: ['d1', 'd2'] params: 'p1' out: 'out' arrayPolicy: # default values in: 'any' params: 'all' , (input, groups, out) -> chai.expect(c.params.p1).to.deep.equal { 0: 1, 1: 2, 2: 3 } chai.expect(input.d1).to.deep.equal {0: 1} chai.expect(input.d2).to.equal 'foo' done() d2.send 'foo' d2.disconnect() d11.send 1 d11.disconnect() p11.send 1 p11.disconnect() p12.send 2 p12.disconnect() p13.send 3 p13.disconnect() it 'should wait for any param and all data values', (done) -> noflo.helpers.WirePattern c, in: ['d1', 'd2'] params: 'p1' out: 'out' arrayPolicy: # inversed in: 'all' params: 'any' , (input, groups, out) -> chai.expect(c.params.p1).to.deep.equal {0: 1} chai.expect(input.d1).to.deep.equal { 0: 1, 1: 2, 2: 3 } chai.expect(input.d2).to.equal 'foo' done() out.on 'disconnect', -> console.log 'disc' d2.send 'foo' d2.disconnect() p11.send 1 p11.disconnect() d11.send 1 d11.disconnect() d12.send 2 d12.disconnect() d13.send 3 d13.disconnect() p12.send 2 p12.disconnect() p13.send 3 p13.disconnect() it 'should wait for all indexes of a single input', (done) -> noflo.helpers.WirePattern c, in: 'd1' out: 'out' arrayPolicy: in: 'all' , (input, groups, out) -> chai.expect(input).to.deep.equal { 0: 1, 1: 2, 2: 3 } done() d11.send 1 d11.disconnect() d12.send 2 d12.disconnect() d13.send 3 d13.disconnect() it 'should behave normally with string output from another component', (done) -> c = new noflo.Component c.inPorts.add 'd1', datatype: 'string' addressable: true c.outPorts.add 'out', datatype: 'object' d11 = noflo.internalSocket.createSocket() d12 = noflo.internalSocket.createSocket() d13 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.d1.attach d11 c.inPorts.d1.attach d12 c.inPorts.d1.attach d13 c.outPorts.out.attach out c2 = new noflo.Component c2.inPorts.add 'in', datatype: 'string' c2.outPorts.add 'out', datatype: 'string' noflo.helpers.WirePattern c2, in: 'in' out: 'out' forwardGroups: true , (input, groups, out) -> out.send input d3 = noflo.internalSocket.createSocket() c2.inPorts.in.attach d3 c2.outPorts.out.attach d11 noflo.helpers.WirePattern c, in: 'd1' out: 'out' , (input, groups, out) -> chai.expect(input).to.deep.equal {0: 'My string'} done() d3.send 'My string' d3.disconnect() describe 'when grouping requests', -> c = new noflo.Component c.inPorts.add 'x', datatype: 'int' .add 'y', datatype: 'int' c.outPorts.add 'out', datatype: 'object' x = noflo.internalSocket.createSocket() y = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.outPorts.out.attach out getUuid = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c is 'x' then r else r&0x3|0x8 v.toString 16 isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i generateRequests = (num) -> reqs = {} for i in [1..num] req = id: getUuid() num: i if i % 3 is 0 req.x = i else if i % 7 is 0 req.y = i else req.x = i req.y = 2*i reqs[req.id] = req reqs sendRequests = (reqs, delay) -> for id, req of reqs do (req) -> setTimeout -> if 'x' of req x.beginGroup req.id x.beginGroup 'x' x.beginGroup req.num x.send req.x x.endGroup() x.endGroup() x.endGroup() x.disconnect() if 'y' of req y.beginGroup req.id y.beginGroup 'y' y.beginGroup req.num y.send req.y y.endGroup() y.endGroup() y.endGroup() y.disconnect() , delay*req.num noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'out' async: true forwardGroups: true group: isUuid gcFrequency: 2 # every 2 requests gcTimeout: 0.02 # older than 20ms , (input, groups, out, done) -> setTimeout -> out.send id: groups[0] x: input.x y: input.y done() , 3 it 'should group requests by outer UUID group', (done) -> reqs = generateRequests 10 count = 0 out.on 'data', (data) -> count++ chai.expect(data.x).to.equal reqs[data.id].x chai.expect(data.y).to.equal reqs[data.id].y done() if count is 6 # 6 complete requests processed sendRequests reqs, 10 it 'should collect garbage every N requests', (done) -> # GC dropped 3 timed out packets, 1 should be left chai.expect(Object.keys(c._wpData[null].groupedData)).to.have.lengthOf 1 chai.expect(Object.keys(c._wpData[null].groupedGroups)).to.have.lengthOf 1 chai.expect(Object.keys(c._wpData[null].disconnectData)).to.have.lengthOf 1 done() it 'should be able to drop a request explicitly', (done) -> for key in Object.keys(c._wpData[null].groupedData) c.dropRequest null, key chai.expect(c._wpData[null].groupedData).to.deep.equal {} chai.expect(c._wpData[null].groupedGroups).to.deep.equal {} chai.expect(c._wpData[null].disconnectData).to.deep.equal {} done() describe 'when using scopes', -> c = new noflo.Component inPorts: x: datatype: 'int' y: datatype: 'int' outPorts: out: datatype: 'object' x = noflo.internalSocket.createSocket() y = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.outPorts.out.attach out getUuid = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c is 'x' then r else r&0x3|0x8 v.toString 16 isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i generateRequests = (num) -> reqs = {} for i in [1..num] req = id: getUuid() num: i if i % 3 is 0 req.x = i else if i % 7 is 0 req.y = i else req.x = i req.y = 2*i reqs[req.id] = req reqs sendRequests = (reqs, delay) -> for id, req of reqs do (req) -> setTimeout -> if 'x' of req x.post new noflo.IP 'openBracket', 'x', scope: req.id x.post new noflo.IP 'data', req.x, scope: req.id x.post new noflo.IP 'closeBracket', null, scope: req.id x.disconnect() if 'y' of req y.post new noflo.IP 'openBracket', 'y', scope: req.id y.post new noflo.IP 'data', req.y, scope: req.id y.post new noflo.IP 'closeBracket', null, scope: req.id y.disconnect() , delay*req.num noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'out' async: true forwardGroups: true , (input, groups, out, done, postpone, resume, scope) -> setTimeout -> out.send id: scope x: input.x y: input.y done() , 3 it 'should scope requests by proper UUID', (done) -> reqs = generateRequests 10 count = 0 out.on 'data', (data) -> count++ chai.expect(data.x).to.equal reqs[data.id].x chai.expect(data.y).to.equal reqs[data.id].y done() if count is 6 # 6 complete requests processed sendRequests reqs, 10 describe 'MultiError', -> describe 'with simple sync processes', -> c = new noflo.Component c.inPorts.add 'form', datatype: 'object' handle: (ip) -> return unless ip.type is 'data' payload = ip.data # Validate form unless payload.name and payload.name.match /^\w{3,16}$/ c.error noflo.helpers.CustomError 'Incorrect name', kind: 'form_error' code: 'invalid_name' param: 'name' unless payload.email and payload.email.match /^\w+@\w+\.\w+$/ c.error noflo.helpers.CustomError 'Incorrect email', kind: 'form_error' code: 'invalid_email' param: 'email' unless payload.accept c.error noflo.helpers.CustomError 'Terms have to be accepted', kind: 'form_error' code: 'terms_not_accepted' param: 'accept' # Finish validation return c.fail() if c.hasErrors # Emulating some processing logic here if payload.name is 'DelayLama' # oops c.outPorts.saved.send false c.outPorts.saved.disconnect() return c.fail noflo.helpers.CustomError 'Suspended for a meditation', kind: 'runtime_error' code: 'delay_lama_detected' else c.outPorts.saved.send true c.outPorts.saved.disconnect() c.outPorts.add 'saved', datatype: 'boolean' c.outPorts.add 'error', datatype: 'object' form = new noflo.internalSocket.createSocket() saved = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.form.attach form c.outPorts.saved.attach saved c.outPorts.error.attach err noflo.helpers.MultiError c it 'should support multiple customized error messages', (done) -> errCount = 0 err.on 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'form_error' errCount++ err.on 'disconnect', -> chai.expect(errCount).to.equal 3 done() form.send name: '<NAME>' email: 'missing' form.disconnect() it 'should pass if everything is correct', (done) -> hadData = false saved.removeAllListeners() saved.once 'data', (data) -> chai.expect(data).to.be.true hadData = true saved.once 'disconnect', -> chai.expect(hadData).to.be.true done() err.removeAllListeners() err.on 'data', (data) -> done data form.send name: '<NAME>' email: '<EMAIL>' accept: true form.disconnect() it 'should handle fatals and runtimes normally', (done) -> saved.once 'data', (data) -> chai.expect(data).to.be.false err.removeAllListeners() errCount = 0 err.once 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'runtime_error' errCount++ err.once 'disconnect', -> chai.expect(errCount).to.equal 1 done() form.send name: '<NAME>' email: '<EMAIL>' accept: true form.disconnect() describe 'with async processes and groups', -> c = new noflo.Component c.inPorts.add 'form', datatype: 'object' c.outPorts.add 'saved', datatype: 'boolean' c.outPorts.add 'error', datatype: 'object' form = new noflo.internalSocket.createSocket() saved = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.form.attach form c.outPorts.saved.attach saved c.outPorts.error.attach err noflo.helpers.WirePattern c, in: 'form' out: 'saved' async: true forwardGroups: true name: 'Registration' , (payload, groups, out, callback) -> # Validate form unless payload.name and payload.name.match /^\w{3,16}$/ this.error noflo.helpers.CustomError('Incorrect name', kind: 'form_error' code: 'invalid_name' param: 'name' ), ['e1'] unless payload.email and payload.email.match /^\w+@\w+\.\w+$/ this.error noflo.helpers.CustomError('Incorrect email', kind: 'form_error' code: 'invalid_email' param: 'email' ), ['e2'] unless payload.accept this.error noflo.helpers.CustomError('Terms have to be accepted', kind: 'form_error' code: 'terms_not_accepted' param: 'accept' ), ['e3'] # Finish validation return callback no if this.hasErrors setTimeout -> # Emulating some processing logic here if payload.name is 'DelayLama' # oops out.send false return callback noflo.helpers.CustomError 'Suspended for a meditation', kind: 'runtime_error' code: 'delay_lama_detected' else out.send true callback() , 10 it 'should support multiple error messages and groups and scope', (done) -> expected = [ 'Registration' 'async0' 'e1' 'async0' 'e2' 'async0' 'e3' ] actual = [] errCount = 0 brackets = 0 err.on 'ip', (ip) -> chai.expect(ip.scope).to.equal 'foo' if ip.type is 'openBracket' brackets++ return actual.push ip.data if ip.type is 'data' data = ip.data chai.expect(data).to.be.an.error chai.expect(data.kind).to.equal 'form_error' errCount++ if ip.type is 'closeBracket' brackets-- if brackets is 0 chai.expect(errCount).to.equal 3 chai.expect(actual).to.deep.equal expected done() form.post new noflo.IP 'openBracket', 'async0', scope: 'foo' form.post new noflo.IP 'data', name: '<NAME>' email: 'missing' , scope: 'foo' form.post new noflo.IP 'closeBracket', 'async0', scope: 'foo' # form.disconnect() it 'should pass if everything is correct', (done) -> hadData = false saved.removeAllListeners() saved.once 'data', (data) -> chai.expect(data).to.be.true hadData = true saved.once 'disconnect', -> chai.expect(hadData).to.be.true done() err.removeAllListeners() err.on 'data', (data) -> done data form.send name: '<NAME>' email: '<EMAIL>' accept: true form.disconnect() it 'should handle fatals and runtimes normally', (done) -> saved.once 'data', (data) -> chai.expect(data).to.be.false err.removeAllListeners() errCount = 0 grpCount = 0 err.on 'begingroup', (grp) -> chai.expect(grp).to.equal 'Registration' grpCount++ err.once 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'runtime_error' errCount++ err.once 'disconnect', -> chai.expect(errCount).to.equal 1 chai.expect(grpCount).to.equal 1 done() form.send name: '<NAME>' email: '<EMAIL>' accept: true form.disconnect() it 'should reset state if component is shut down', (done) -> c2 = new noflo.Component c2.inPorts.add 'name', datatype: 'string' handle: (ip) -> return unless ip.type is 'data' c2.error new Error "The name will never pass!" noflo.helpers.MultiError c2 ins = new noflo.internalSocket.createSocket() c2.inPorts.name.attach ins ins.send '<NAME>' chai.expect(c2.hasErrors).to.be.true chai.expect(c2.errors).to.be.an 'array' chai.expect(c2.errors).to.have.lengthOf 1 c2.shutdown() chai.expect(c2.hasErrors).to.be.false chai.expect(c2.errors).to.be.an 'array' chai.expect(c2.errors).to.have.lengthOf 0 done()
true
if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/ chai = require 'chai' unless chai noflo = require '../src/lib/NoFlo.coffee' else noflo = require 'noflo' describe 'Component traits', -> describe 'MapComponent', -> c = null it 'should pass data to the callback', -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data) -> chai.expect(data).to.equal 1 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s.send 1 it 'should pass groups to the callback', -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data, groups) -> chai.expect(groups).to.eql [ 'one' 'two' ] chai.expect(data).to.equal 1 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s.beginGroup 'one' s.beginGroup 'two' s.send 1 it 'should send groups and disconnect through', (done) -> c = new noflo.Component c.inPorts.add 'in' c.outPorts.add 'out', required: false noflo.helpers.MapComponent c, (data, groups, out) -> out.send data * 2 s = new noflo.internalSocket.createSocket() c.inPorts.in.attach s s2 = new noflo.internalSocket.createSocket() c.outPorts.out.attach s2 groups = [] s2.on 'begingroup', (group) -> groups.push group s2.on 'data', (data) -> chai.expect(groups.length).to.equal 2 chai.expect(data).to.equal 6 s2.on 'endgroup', -> groups.pop() s2.on 'disconnect', -> chai.expect(groups.length).to.equal 0 done() s.beginGroup 'one' s.beginGroup 'two' s.send 3 s.endGroup() s.endGroup() s.disconnect() describe 'WirePattern', -> describe 'when grouping by packet groups', -> c = null x = null y = null z = null p = null before (done) -> c = new noflo.Component c.inPorts.add 'x', required: true datatype: 'int' .add 'y', required: true datatype: 'int' .add 'z', required: true datatype: 'int' c.outPorts.add 'point' x = new noflo.internalSocket.createSocket() y = new noflo.internalSocket.createSocket() z = new noflo.internalSocket.createSocket() p = new noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.inPorts.z.attach z c.outPorts.point.attach p done() it 'should pass data and groups to the callback', (done) -> src = 111: {x: 1, y: 2, z: 3} 222: {x: 4, y: 5, z: 6} 333: {x: 7, y: 8, z: 9} noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' group: true forwardGroups: true , (data, groups, out) -> chai.expect(groups.length).to.be.above 0 chai.expect(data).to.deep.equal src[groups[0]] out.send data groups = [] count = 0 p.on 'begingroup', (grp) -> groups.push grp p.on 'endgroup', -> groups.pop() p.on 'data', (data) -> count++ p.on 'disconnect', -> done() if count is 3 and groups.length is 0 for key, grp of src x.beginGroup key y.beginGroup key z.beginGroup key x.send grp.x y.send grp.y z.send grp.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should work without a group provided', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' , (data, groups, out) -> chai.expect(groups.length).to.equal 0 out.send {x: data.x, y: data.y, z: data.z} p.once 'data', (data) -> chai.expect(data).to.deep.equal {x: 123, y: 456, z: 789} done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() it 'should process inputs for different groups independently with group: true', (done) -> src = 1: {x: 1, y: 2, z: 3} 2: {x: 4, y: 5, z: 6} 3: {x: 7, y: 8, z: 9} inOrder = [ [ 1, 'x' ] [ 3, 'z' ] [ 2, 'y' ] [ 2, 'x' ] [ 1, 'z' ] [ 2, 'z' ] [ 3, 'x' ] [ 1, 'y' ] [ 3, 'y' ] ] outOrder = [ 2, 1, 3 ] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' group: true forwardGroups: true , (data, groups, out) -> out.send {x: data.x, y: data.y, z: data.z} groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'endgroup', (grp) -> groups.pop() p.on 'data', (data) -> chai.expect(groups.length).to.equal 1 chai.expect(groups[0]).to.equal outOrder[0] chai.expect(data).to.deep.equal src[outOrder[0]] outOrder.shift() done() unless outOrder.length for tuple in inOrder input = null switch tuple[1] when 'x' input = x when 'y' input = y when 'z' input = z input.beginGroup tuple[0] input.send src[tuple[0]][tuple[1]] input.endGroup() input.disconnect() it 'should support asynchronous handlers', (done) -> point = x: 123 y: 456 z: 789 noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' async: true group: true forwardGroups: true , (data, groups, out, callback) -> setTimeout -> out.send {x: data.x, y: data.y, z: data.z} callback() , 100 p.removeAllListeners() counter = 0 hadData = false p.on 'begingroup', (grp) -> counter++ p.on 'endgroup', -> counter-- p.once 'data', (data) -> chai.expect(data).to.deep.equal point hadData = true p.once 'disconnect', -> chai.expect(counter).to.equal 0 chai.expect(hadData).to.be.true done() x.beginGroup 'async' y.beginGroup 'async' z.beginGroup 'async' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should not forward groups if forwarding is off', (done) -> point = x: 123 y: 456 noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'point' , (data, groups, out) -> out.send { x: data.x, y: data.y } p.removeAllListeners() counter = 0 hadData = false p.on 'begingroup', (grp) -> counter++ p.on 'data', (data) -> chai.expect(data).to.deep.equal point hadData = true p.once 'disconnect', -> chai.expect(counter).to.equal 0 chai.expect(hadData).to.be.true done() x.beginGroup 'doNotForwardMe' y.beginGroup 'doNotForwardMe' x.send point.x y.send point.y x.endGroup() y.endGroup() x.disconnect() y.disconnect() it 'should forward groups from a specific port only', (done) -> point = x: 123 y: 456 z: 789 refGroups = ['boo'] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' forwardGroups: 'y' , (data, groups, out) -> out.send { x: data.x, y: data.y, z: data.z } p.removeAllListeners() groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'data', (data) -> chai.expect(data).to.deep.equal point p.once 'disconnect', -> chai.expect(groups).to.deep.equal refGroups done() x.beginGroup 'foo' y.beginGroup 'boo' z.beginGroup 'bar' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() it 'should forward groups from selected ports only', (done) -> point = x: 123 y: 456 z: 789 refGroups = ['foo', 'bar'] noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' forwardGroups: [ 'x', 'z' ] , (data, groups, out) -> out.send { x: data.x, y: data.y, z: data.z } p.removeAllListeners() groups = [] p.on 'begingroup', (grp) -> groups.push grp p.on 'data', (data) -> chai.expect(data).to.deep.equal point p.once 'disconnect', -> chai.expect(groups).to.deep.equal refGroups done() x.beginGroup 'foo' y.beginGroup 'boo' z.beginGroup 'bar' x.send point.x y.send point.y z.send point.z x.endGroup() y.endGroup() z.endGroup() x.disconnect() y.disconnect() z.disconnect() describe 'when `this` context is important', -> c = new noflo.Component c.inPorts.add 'x', required: true datatype: 'int' .add 'y', required: true datatype: 'int' .add 'z', required: true datatype: 'int' c.outPorts.add 'point' x = new noflo.internalSocket.createSocket() y = new noflo.internalSocket.createSocket() z = new noflo.internalSocket.createSocket() p = new noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.inPorts.z.attach z c.outPorts.point.attach p it 'should correctly bind component to `this` context', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] out: 'point' , (data, groups, out) -> chai.expect(this).to.deep.equal c out.send {x: data.x, y: data.y, z: data.z} p.once 'data', (data) -> chai.expect(data).to.deep.equal {x: 123, y: 456, z: 789} done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() it 'should correctly bind component to `this` context in async mode', (done) -> p.removeAllListeners() noflo.helpers.WirePattern c, in: ['x', 'y', 'z'] async: true out: 'point' , (data, groups, out, callback) -> chai.expect(this).to.deep.equal c out.send {x: data.x, y: data.y, z: data.z} callback() p.once 'data', (data) -> done() x.send 123 x.disconnect() y.send 456 y.disconnect() z.send 789 z.disconnect() describe 'when in async mode and packet order matters', -> c = new noflo.Component c.inPorts.add 'delay', datatype: 'int' .add 'msg', datatype: 'string' c.outPorts.add 'out', datatype: 'object' .add 'load', datatype: 'int' delay = new noflo.internalSocket.createSocket() msg = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() load = new noflo.internalSocket.createSocket() c.inPorts.delay.attach delay c.inPorts.msg.attach msg c.outPorts.out.attach out c.outPorts.load.attach load it 'should preserve input order at the output', (done) -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false , (data, groups, res, callback) -> setTimeout -> res.send { delay: data.delay, msg: data.msg } callback() , data.delay sample = [ { delay: 30, msg: "one" } { delay: 0, msg: "two" } { delay: 20, msg: "three" } { delay: 10, msg: "four" } ] out.on 'data', (data) -> chai.expect(data).to.deep.equal sample.shift() out.on 'disconnect', -> done() if sample.length is 0 expected = [1, 2, 3, 4, 3, 2, 1, 0] load.on 'data', (data) -> chai.expect(data).to.equal expected.shift() idx = 0 for ip in sample delay.beginGroup idx delay.send ip.delay delay.endGroup() msg.beginGroup idx msg.send ip.msg msg.endGroup() delay.disconnect() msg.disconnect() idx++ it 'should throw if receiveStreams is used', (done) -> f = -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false receiveStreams: ['delay', 'msg'] , (data, groups, res, callback) -> callback() chai.expect(f).to.throw Error done() it 'should throw if sendStreams is used', (done) -> f = -> noflo.helpers.WirePattern c, in: ['delay', 'msg'] async: true ordered: true group: false sendStreams: ['out'] , (data, groups, res, callback) -> callback() chai.expect(f).to.throw Error done() # it 'should support complex substreams', (done) -> # out.removeAllListeners() # load.removeAllListeners() # c.cntr = 0 # helpers.WirePattern c, # in: ['delay', 'msg'] # async: true # ordered: true # group: false # receiveStreams: ['delay', 'msg'] # , (data, groups, res, callback) -> # # Substream to object conversion validation # # (the hard way) # chai.expect(data.delay instanceof Substream).to.be.true # chai.expect(data.msg instanceof Substream).to.be.true # delayObj = data.delay.toObject() # msgObj = data.msg.toObject() # index0 = this.cntr.toString() # chai.expect(Object.keys(delayObj)[0]).to.equal index0 # chai.expect(Object.keys(msgObj)[0]).to.equal index0 # subDelay = delayObj[index0] # subMsg = msgObj[index0] # index1 = (10 + this.cntr).toString() # chai.expect(Object.keys(subDelay)[0]).to.equal index1 # chai.expect(Object.keys(subMsg)[0]).to.equal index1 # delayData = subDelay[index1] # msgData = subMsg[index1] # chai.expect(delayData).to.equal sample[c.cntr].delay # chai.expect(msgData).to.equal sample[c.cntr].msg # this.cntr++ # setTimeout -> # # Substream tree traversal (the easy way) # for k0, v0 of msgObj # res.beginGroup k0 # res.send k0 # for k1, v1 of v0 # res.beginGroup k1 # res.send # delay: delayObj[k0][k1] # msg: msgObj[k0][k1] # res.endGroup() # res.send k1 # res.endGroup() # callback() # , data.delay # sample = [ # { delay: 30, msg: "one" } # { delay: 0, msg: "two" } # { delay: 20, msg: "three" } # { delay: 10, msg: "four" } # ] # expected = [ # '0', '0', '10', sample[0], '10' # '1', '1', '11', sample[1], '11' # '2', '2', '12', sample[2], '12' # '3', '3', '13', sample[3], '13' # ] # out.on 'begingroup', (grp) -> # chai.expect(grp).to.equal expected.shift() # out.on 'data', (data) -> # chai.expect(data).to.deep.equal expected.shift() # out.on 'disconnect', -> # done() if expected.length is 0 # for i in [0..3] # delay.beginGroup i # delay.beginGroup 10 + i # delay.send sample[i].delay # delay.endGroup() # delay.endGroup() # msg.beginGroup i # msg.beginGroup 10 + i # msg.send sample[i].msg # msg.endGroup() # msg.endGroup() # delay.disconnect() # msg.disconnect() describe 'when grouping by field', -> c = new noflo.Component c.inPorts.add 'user', datatype: 'object' .add 'message', datatype: 'object' c.outPorts.add 'signedmessage' usr = new noflo.internalSocket.createSocket() msg = new noflo.internalSocket.createSocket() umsg = new noflo.internalSocket.createSocket() c.inPorts.user.attach usr c.inPorts.message.attach msg c.outPorts.signedmessage.attach umsg it 'should match objects by specific field', (done) -> noflo.helpers.WirePattern c, in: ['user', 'message'] out: 'signedmessage' async: true field: 'request' , (data, groups, out, callback) -> setTimeout -> out.send request: data.request user: data.user.name text: data.message.text callback() , 10 users = 14: {request: 14, id: 21, name: 'PI:NAME:<NAME>END_PI'} 12: {request: 12, id: 25, name: 'PI:NAME:<NAME>END_PI'} 34: {request: 34, id: 84, name: 'PI:NAME:<NAME>END_PI'} messages = 34: {request: 34, id: 234, text: 'Hello world'} 12: {request: 12, id: 82, text: 'Aloha amigos'} 14: {request: 14, id: 249, text: 'Node.js ftw'} counter = 0 umsg.on 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.request).to.be.ok chai.expect(data.user).to.equal users[data.request].name chai.expect(data.text).to.equal messages[data.request].text counter++ done() if counter is 3 # Send input asynchronously with mixed delays for req, user of users do (req, user) -> setTimeout -> usr.send user usr.disconnect() , req for req, mesg of messages do (req, mesg) -> setTimeout -> msg.send mesg msg.disconnect() , req describe 'when there are multiple output routes', -> c = new noflo.Component c.inPorts.add 'num', datatype: 'int' .add 'str', datatype: 'string' c.outPorts.add 'odd', datatype: 'object' .add 'even', datatype: 'object' num = new noflo.internalSocket.createSocket() str = new noflo.internalSocket.createSocket() odd = new noflo.internalSocket.createSocket() even = new noflo.internalSocket.createSocket() c.inPorts.num.attach num c.inPorts.str.attach str c.outPorts.odd.attach odd c.outPorts.even.attach even it 'should send output to one or more of them', (done) -> numbers = ['cero', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'] noflo.helpers.WirePattern c, in: ['num', 'str'] out: ['odd', 'even'] async: true ordered: true , (data, groups, outs, callback) -> setTimeout -> if data.num % 2 is 1 outs.odd.beginGroup grp for grp in groups outs.odd.send data outs.odd.endGroup() for grp in groups else outs.even.beginGroup grp for grp in groups outs.even.send data outs.even.endGroup() for grp in groups callback() , 0 grpCounter = 0 dataCounter = 0 odd.on 'begingroup', (grp) -> grpCounter++ odd.on 'data', (data) -> chai.expect(data.num % 2).to.equal 1 chai.expect(data.str).to.equal numbers[data.num] dataCounter++ odd.on 'disconnect', -> done() if dataCounter is 10 and grpCounter is 10 even.on 'begingroup', (grp) -> grpCounter++ even.on 'data', (data) -> chai.expect(data.num % 2).to.equal 0 chai.expect(data.str).to.equal numbers[data.num] dataCounter++ even.on 'disconnect', -> done() if dataCounter is 10 and grpCounter is 10 for i in [0...10] num.beginGroup i num.send i num.endGroup i num.disconnect() str.beginGroup i str.send numbers[i] str.endGroup i str.disconnect() describe 'when there are parameter ports', -> c = null p1 = p2 = p3 = d1 = d2 = out = err = 0 beforeEach -> c = new noflo.Component c.inPorts.add 'param1', datatype: 'string' required: true .add 'param2', datatype: 'int' required: false .add 'param3', datatype: 'int' required: true default: 0 .add 'data1', datatype: 'string' .add 'data2', datatype: 'int' c.outPorts.add 'out', datatype: 'object' .add 'error', datatype: 'object' p1 = new noflo.internalSocket.createSocket() p2 = new noflo.internalSocket.createSocket() p3 = new noflo.internalSocket.createSocket() d1 = new noflo.internalSocket.createSocket() d2 = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.param1.attach p1 c.inPorts.param2.attach p2 c.inPorts.param3.attach p3 c.inPorts.data1.attach d1 c.inPorts.data2.attach d2 c.outPorts.out.attach out c.outPorts.error.attach err it 'should wait for required params without default value', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.be.undefined chai.expect(data.p3).to.equal 0 chai.expect(data.d1).to.equal 'foo' chai.expect(data.d2).to.equal 123 # And later when second param arrives out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 568 chai.expect(data.p3).to.equal 800 chai.expect(data.d1).to.equal 'bar' chai.expect(data.d2).to.equal 456 done() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() c.sendDefaults() p1.send 'req' p1.disconnect() # the handler should be triggered here setTimeout -> p2.send 568 p2.disconnect() p3.send 800 p3.disconnect() d1.send 'bar' d1.disconnect() d2.send 456 d2.disconnect() , 10 it 'should work for async procs too', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> delay = if c.params.param2 then c.params.param2 else 10 setTimeout -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res , delay out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 56 chai.expect(data.p3).to.equal 0 chai.expect(data.d1).to.equal 'foo' chai.expect(data.d2).to.equal 123 done() p2.send 56 p2.disconnect() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() c.sendDefaults() p1.send 'req' p1.disconnect() # the handler should be triggered here it 'should reset state if shutdown() is called', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] , (input, groups, out) -> out.send p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 d1.send 'boo' d1.disconnect() p2.send 73 p2.disconnect() chai.expect(Object.keys(c._wpData[null].groupedData)).to.have.length.above 0 chai.expect(Object.keys(c._wpData[null].params)).to.have.length.above 0 c.shutdown() chai.expect(c._wpData).to.deep.equal {} done() it 'should drop premature data if configured to do so', (done) -> noflo.helpers.WirePattern c, in: ['data1', 'data2'] out: 'out' params: ['param1', 'param2', 'param3'] dropInput: true , (input, groups, out) -> res = p1: c.params.param1 p2: c.params.param2 p3: c.params.param3 d1: input.data1 d2: input.data2 out.send res out.once 'data', (data) -> chai.expect(data).to.be.an 'object' chai.expect(data.p1).to.equal 'req' chai.expect(data.p2).to.equal 568 chai.expect(data.p3).to.equal 800 chai.expect(data.d1).to.equal 'bar' chai.expect(data.d2).to.equal 456 done() c.sendDefaults() p2.send 568 p2.disconnect() p3.send 800 p3.disconnect() d1.send 'foo' d1.disconnect() d2.send 123 d2.disconnect() # Data is dropped at this point setTimeout -> p1.send 'req' p1.disconnect() d1.send 'bar' d1.disconnect() d2.send 456 d2.disconnect() , 10 describe 'without output ports', -> c = new noflo.Component c.inPorts.add 'foo' foo = noflo.internalSocket.createSocket() sig = noflo.internalSocket.createSocket() c.inPorts.foo.attach foo noflo.helpers.WirePattern c, in: 'foo' out: [] async: true , (foo, grp, out, callback) -> setTimeout -> sig.send foo callback() , 20 it 'should be fine still', (done) -> sig.on 'data', (data) -> chai.expect(data).to.equal 'foo' done() foo.send 'foo' foo.disconnect() describe 'when data processing is not possible at the moment', -> c = new noflo.Component c.inPorts.add 'line', datatype: 'string' .add 'repeat', datatype: 'int' .add 'when', datatype: 'string' default: 'later' c.outPorts.add 'res', datatype: 'string' .add 'error', datatype: 'object' line = noflo.internalSocket.createSocket() rpt = noflo.internalSocket.createSocket() whn = noflo.internalSocket.createSocket() res = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.line.attach line c.inPorts.repeat.attach rpt c.inPorts.when.attach whn c.outPorts.res.attach res c.outPorts.error.attach err c.invCount = 0 tryAgain = null noflo.helpers.WirePattern c, in: ['line', 'repeat'] params: 'when' out: 'res' async: true , (input, groups, out, completed, postpone, resume) -> this.invCount++ return if this.invCount > 100 # avoid deadlocks just in case switch this.params.when when 'now' repeated = '' repeated += input.line for i in [0...input.repeat] out.send repeated completed() when 'later' postpone() when 'afterTimeout' postpone false this.params.when = 'now' # don't recurse forever setTimeout -> resume() , 10 when 'whenItell' postpone false this.params.when = 'now' # don't recurse forever tryAgain = resume it 'should be able to postpone it until next tuple of data', (done) -> res.once 'data', (data) -> chai.expect(data).to.equal 'opopopopopopopopopop' chai.expect(c.invCount).to.equal 2 res.once 'data', (data) -> chai.expect(data).to.equal 'gogogo' chai.expect(c.invCount).to.equal 3 done() c.sendDefaults() line.send 'op' rpt.send 10 line.disconnect() rpt.disconnect() # no output expected at this point whn.send 'now' whn.disconnect() line.send 'go' rpt.send 3 line.disconnect() rpt.disconnect() # this flushes the earlier stuff it 'should be able to postpone and retry after timeout', (done) -> c.invCount = 0 res.once 'data', (data) -> chai.expect(data).to.equal 'dododo' chai.expect(c.invCount).to.equal 2 done() whn.send 'afterTimeout' whn.disconnect() line.send 'do' rpt.send 3 line.disconnect() rpt.disconnect() it 'should be able to postpone it and resume when needed', (done) -> c.invCount = 0 res.once 'data', (data) -> chai.expect(data).to.equal 'yoyo' chai.expect(c.invCount).to.equal 2 done() whn.send 'whenItell' whn.disconnect() line.send 'yo' rpt.send 2 line.disconnect() rpt.disconnect() # Here tryAgain got the resume callback setTimeout -> tryAgain() , 30 describe 'with many inputs and groups', -> c = new noflo.Component c.token = null c.inPorts.add 'in', datatype: 'string' .add 'message', datatype: 'string' .add 'repository', datatype: 'string' .add 'path', datatype: 'string' .add 'token', datatype: 'string', (event, payload) -> c.token = payload if event is 'data' c.outPorts.add 'out', datatype: 'string' .add 'error', datatype: 'object' noflo.helpers.WirePattern c, in: ['in', 'message', 'repository', 'path'] out: 'out' async: true forwardGroups: true , (data, groups, out, callback) -> setTimeout -> out.beginGroup data.path out.send data.message out.endGroup() do callback , 300 ins = noflo.internalSocket.createSocket() msg = noflo.internalSocket.createSocket() rep = noflo.internalSocket.createSocket() pth = noflo.internalSocket.createSocket() tkn = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.in.attach ins c.inPorts.message.attach msg c.inPorts.repository.attach rep c.inPorts.path.attach pth c.inPorts.token.attach tkn c.outPorts.out.attach out c.outPorts.error.attach err it 'should handle mixed flow well', (done) -> groups = [] refGroups = [ 'foo' 'http://techcrunch.com/2013/03/26/embedly-now/' 'path data' ] ends = 0 packets = [] refData = ['message data'] out.on 'begingroup', (grp) -> groups.push grp out.on 'endgroup', -> ends++ out.on 'data', (data) -> packets.push data out.on 'disconnect', -> chai.expect(groups).to.deep.equal refGroups chai.expect(ends).to.equal 3 chai.expect(packets).to.deep.equal refData done() err.on 'data', (data) -> done data rep.beginGroup 'foo' rep.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' rep.send 'repo data' rep.endGroup() rep.endGroup() ins.beginGroup 'foo' ins.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' ins.send 'ins data' msg.beginGroup 'foo' msg.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' msg.send 'message data' msg.endGroup() msg.endGroup() ins.endGroup() ins.endGroup() ins.disconnect() msg.disconnect() pth.beginGroup 'foo' pth.beginGroup 'http://techcrunch.com/2013/03/26/embedly-now/' pth.send 'path data' pth.endGroup() pth.endGroup() pth.disconnect() rep.disconnect() describe 'for batch processing', -> # Component constructors newGenerator = (name) -> generator = new noflo.Component generator.inPorts.add 'count', datatype: 'int' generator.outPorts.add 'seq', datatype: 'int' noflo.helpers.WirePattern generator, in: 'count' out: 'seq' async: true forwardGroups: true ordered: true , (count, groups, seq, callback) -> sentCount = 0 for i in [1..count] do (i) -> delay = if i > 10 then i % 10 else i setTimeout -> seq.send i sentCount++ if sentCount is count callback() , delay newDoubler = (name) -> doubler = new noflo.Component doubler.inPorts.add 'num', datatype: 'int' doubler.outPorts.add 'out', datatype: 'int' noflo.helpers.WirePattern doubler, in: 'num' out: 'out' forwardGroups: true , (num, groups, out) -> dbl = 2*num out.send dbl newAdder = -> adder = new noflo.Component adder.inPorts.add 'num1', datatype: 'int' adder.inPorts.add 'num2', datatype: 'int' adder.outPorts.add 'sum', datatype: 'int' noflo.helpers.WirePattern adder, in: ['num1', 'num2'] out: 'sum' forwardGroups: true async: true ordered: true , (args, groups, out, callback) -> sum = args.num1 + args.num2 # out.send sum setTimeout -> out.send sum callback() , sum % 10 newSeqsum = -> seqsum = new noflo.Component seqsum.sum = 0 seqsum.inPorts.add 'seq', datatype: 'int', (event, payload) -> switch event when 'data' seqsum.sum += payload when 'disconnect' seqsum.outPorts.sum.send seqsum.sum seqsum.sum = 0 seqsum.outPorts.sum.disconnect() seqsum.outPorts.add 'sum', datatype: 'int' return seqsum # Wires genA = newGenerator 'A' genB = newGenerator 'B' dblA = newDoubler 'A' dblB = newDoubler 'B' addr = newAdder() sumr = newSeqsum() cntA = noflo.internalSocket.createSocket() cntB = noflo.internalSocket.createSocket() gen2dblA = noflo.internalSocket.createSocket() gen2dblB = noflo.internalSocket.createSocket() dblA2add = noflo.internalSocket.createSocket() dblB2add = noflo.internalSocket.createSocket() addr2sum = noflo.internalSocket.createSocket() sum = noflo.internalSocket.createSocket() genA.inPorts.count.attach cntA genB.inPorts.count.attach cntB genA.outPorts.seq.attach gen2dblA genB.outPorts.seq.attach gen2dblB dblA.inPorts.num.attach gen2dblA dblB.inPorts.num.attach gen2dblB dblA.outPorts.out.attach dblA2add dblB.outPorts.out.attach dblB2add addr.inPorts.num1.attach dblA2add addr.inPorts.num2.attach dblB2add addr.outPorts.sum.attach addr2sum sumr.inPorts.seq.attach addr2sum sumr.outPorts.sum.attach sum it 'should process sequences of packets separated by disconnects', (done) -> expected = [ 24, 40 ] actual = [] sum.on 'data', (data) -> actual.push data sum.on 'disconnect', -> chai.expect(actual).to.have.length.above 0 chai.expect(expected).to.have.length.above 0 act = actual.shift() exp = expected.shift() chai.expect(act).to.equal exp done() if expected.length is 0 cntA.send 3 cntA.disconnect() cntB.send 3 cntB.disconnect() cntA.send 4 cntB.send 4 cntA.disconnect() cntB.disconnect() describe 'for batch processing with groups', -> c1 = new noflo.Component c1.inPorts.add 'count', datatype: 'int' c1.outPorts.add 'seq', datatype: 'int' c2 = new noflo.Component c2.inPorts.add 'num', datatype: 'int' c2.outPorts.add 'out', datatype: 'int' cnt = noflo.internalSocket.createSocket() c1c2 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c1.inPorts.count.attach cnt c1.outPorts.seq.attach c1c2 c2.inPorts.num.attach c1c2 c2.outPorts.out.attach out it 'should wrap entire sequence with groups', (done) -> noflo.helpers.WirePattern c1, in: 'count' out: 'seq' async: true forwardGroups: true , (count, groups, out, callback) -> for i in [0...count] do (i) -> setTimeout -> out.send i , 0 setTimeout -> callback() , 3 noflo.helpers.WirePattern c2, in: 'num' out: 'out' forwardGroups: true , (num, groups, out) -> chai.expect(groups).to.deep.equal ['foo', 'bar'] out.send num expected = ['<foo>', '<bar>', 0, 1, 2, '</bar>', '</foo>'] actual = [] out.on 'begingroup', (grp) -> actual.push "<#{grp}>" out.on 'endgroup', (grp) -> actual.push "</#{grp}>" out.on 'data', (data) -> actual.push data out.on 'disconnect', -> chai.expect(actual).to.deep.equal expected done() cnt.beginGroup 'foo' cnt.beginGroup 'bar' cnt.send 3 cnt.endGroup() cnt.endGroup() cnt.disconnect() describe 'with addressable ports', -> c = new noflo.Component c.inPorts.add 'p1', datatype: 'int' addressable: true required: true .add 'd1', datatype: 'int' addressable: true .add 'd2', datatype: 'string' c.outPorts.add 'out', datatype: 'object' .add 'error', datatype: 'object' p11 = noflo.internalSocket.createSocket() p12 = noflo.internalSocket.createSocket() p13 = noflo.internalSocket.createSocket() d11 = noflo.internalSocket.createSocket() d12 = noflo.internalSocket.createSocket() d13 = noflo.internalSocket.createSocket() d2 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() err = noflo.internalSocket.createSocket() c.inPorts.p1.attach p11 c.inPorts.p1.attach p12 c.inPorts.p1.attach p13 c.inPorts.d1.attach d11 c.inPorts.d1.attach d12 c.inPorts.d1.attach d13 c.inPorts.d2.attach d2 c.outPorts.out.attach out c.outPorts.error.attach err it 'should wait for all param and any data port values (default)', (done) -> noflo.helpers.WirePattern c, in: ['d1', 'd2'] params: 'p1' out: 'out' arrayPolicy: # default values in: 'any' params: 'all' , (input, groups, out) -> chai.expect(c.params.p1).to.deep.equal { 0: 1, 1: 2, 2: 3 } chai.expect(input.d1).to.deep.equal {0: 1} chai.expect(input.d2).to.equal 'foo' done() d2.send 'foo' d2.disconnect() d11.send 1 d11.disconnect() p11.send 1 p11.disconnect() p12.send 2 p12.disconnect() p13.send 3 p13.disconnect() it 'should wait for any param and all data values', (done) -> noflo.helpers.WirePattern c, in: ['d1', 'd2'] params: 'p1' out: 'out' arrayPolicy: # inversed in: 'all' params: 'any' , (input, groups, out) -> chai.expect(c.params.p1).to.deep.equal {0: 1} chai.expect(input.d1).to.deep.equal { 0: 1, 1: 2, 2: 3 } chai.expect(input.d2).to.equal 'foo' done() out.on 'disconnect', -> console.log 'disc' d2.send 'foo' d2.disconnect() p11.send 1 p11.disconnect() d11.send 1 d11.disconnect() d12.send 2 d12.disconnect() d13.send 3 d13.disconnect() p12.send 2 p12.disconnect() p13.send 3 p13.disconnect() it 'should wait for all indexes of a single input', (done) -> noflo.helpers.WirePattern c, in: 'd1' out: 'out' arrayPolicy: in: 'all' , (input, groups, out) -> chai.expect(input).to.deep.equal { 0: 1, 1: 2, 2: 3 } done() d11.send 1 d11.disconnect() d12.send 2 d12.disconnect() d13.send 3 d13.disconnect() it 'should behave normally with string output from another component', (done) -> c = new noflo.Component c.inPorts.add 'd1', datatype: 'string' addressable: true c.outPorts.add 'out', datatype: 'object' d11 = noflo.internalSocket.createSocket() d12 = noflo.internalSocket.createSocket() d13 = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.d1.attach d11 c.inPorts.d1.attach d12 c.inPorts.d1.attach d13 c.outPorts.out.attach out c2 = new noflo.Component c2.inPorts.add 'in', datatype: 'string' c2.outPorts.add 'out', datatype: 'string' noflo.helpers.WirePattern c2, in: 'in' out: 'out' forwardGroups: true , (input, groups, out) -> out.send input d3 = noflo.internalSocket.createSocket() c2.inPorts.in.attach d3 c2.outPorts.out.attach d11 noflo.helpers.WirePattern c, in: 'd1' out: 'out' , (input, groups, out) -> chai.expect(input).to.deep.equal {0: 'My string'} done() d3.send 'My string' d3.disconnect() describe 'when grouping requests', -> c = new noflo.Component c.inPorts.add 'x', datatype: 'int' .add 'y', datatype: 'int' c.outPorts.add 'out', datatype: 'object' x = noflo.internalSocket.createSocket() y = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.outPorts.out.attach out getUuid = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c is 'x' then r else r&0x3|0x8 v.toString 16 isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i generateRequests = (num) -> reqs = {} for i in [1..num] req = id: getUuid() num: i if i % 3 is 0 req.x = i else if i % 7 is 0 req.y = i else req.x = i req.y = 2*i reqs[req.id] = req reqs sendRequests = (reqs, delay) -> for id, req of reqs do (req) -> setTimeout -> if 'x' of req x.beginGroup req.id x.beginGroup 'x' x.beginGroup req.num x.send req.x x.endGroup() x.endGroup() x.endGroup() x.disconnect() if 'y' of req y.beginGroup req.id y.beginGroup 'y' y.beginGroup req.num y.send req.y y.endGroup() y.endGroup() y.endGroup() y.disconnect() , delay*req.num noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'out' async: true forwardGroups: true group: isUuid gcFrequency: 2 # every 2 requests gcTimeout: 0.02 # older than 20ms , (input, groups, out, done) -> setTimeout -> out.send id: groups[0] x: input.x y: input.y done() , 3 it 'should group requests by outer UUID group', (done) -> reqs = generateRequests 10 count = 0 out.on 'data', (data) -> count++ chai.expect(data.x).to.equal reqs[data.id].x chai.expect(data.y).to.equal reqs[data.id].y done() if count is 6 # 6 complete requests processed sendRequests reqs, 10 it 'should collect garbage every N requests', (done) -> # GC dropped 3 timed out packets, 1 should be left chai.expect(Object.keys(c._wpData[null].groupedData)).to.have.lengthOf 1 chai.expect(Object.keys(c._wpData[null].groupedGroups)).to.have.lengthOf 1 chai.expect(Object.keys(c._wpData[null].disconnectData)).to.have.lengthOf 1 done() it 'should be able to drop a request explicitly', (done) -> for key in Object.keys(c._wpData[null].groupedData) c.dropRequest null, key chai.expect(c._wpData[null].groupedData).to.deep.equal {} chai.expect(c._wpData[null].groupedGroups).to.deep.equal {} chai.expect(c._wpData[null].disconnectData).to.deep.equal {} done() describe 'when using scopes', -> c = new noflo.Component inPorts: x: datatype: 'int' y: datatype: 'int' outPorts: out: datatype: 'object' x = noflo.internalSocket.createSocket() y = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() c.inPorts.x.attach x c.inPorts.y.attach y c.outPorts.out.attach out getUuid = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c is 'x' then r else r&0x3|0x8 v.toString 16 isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i generateRequests = (num) -> reqs = {} for i in [1..num] req = id: getUuid() num: i if i % 3 is 0 req.x = i else if i % 7 is 0 req.y = i else req.x = i req.y = 2*i reqs[req.id] = req reqs sendRequests = (reqs, delay) -> for id, req of reqs do (req) -> setTimeout -> if 'x' of req x.post new noflo.IP 'openBracket', 'x', scope: req.id x.post new noflo.IP 'data', req.x, scope: req.id x.post new noflo.IP 'closeBracket', null, scope: req.id x.disconnect() if 'y' of req y.post new noflo.IP 'openBracket', 'y', scope: req.id y.post new noflo.IP 'data', req.y, scope: req.id y.post new noflo.IP 'closeBracket', null, scope: req.id y.disconnect() , delay*req.num noflo.helpers.WirePattern c, in: ['x', 'y'] out: 'out' async: true forwardGroups: true , (input, groups, out, done, postpone, resume, scope) -> setTimeout -> out.send id: scope x: input.x y: input.y done() , 3 it 'should scope requests by proper UUID', (done) -> reqs = generateRequests 10 count = 0 out.on 'data', (data) -> count++ chai.expect(data.x).to.equal reqs[data.id].x chai.expect(data.y).to.equal reqs[data.id].y done() if count is 6 # 6 complete requests processed sendRequests reqs, 10 describe 'MultiError', -> describe 'with simple sync processes', -> c = new noflo.Component c.inPorts.add 'form', datatype: 'object' handle: (ip) -> return unless ip.type is 'data' payload = ip.data # Validate form unless payload.name and payload.name.match /^\w{3,16}$/ c.error noflo.helpers.CustomError 'Incorrect name', kind: 'form_error' code: 'invalid_name' param: 'name' unless payload.email and payload.email.match /^\w+@\w+\.\w+$/ c.error noflo.helpers.CustomError 'Incorrect email', kind: 'form_error' code: 'invalid_email' param: 'email' unless payload.accept c.error noflo.helpers.CustomError 'Terms have to be accepted', kind: 'form_error' code: 'terms_not_accepted' param: 'accept' # Finish validation return c.fail() if c.hasErrors # Emulating some processing logic here if payload.name is 'DelayLama' # oops c.outPorts.saved.send false c.outPorts.saved.disconnect() return c.fail noflo.helpers.CustomError 'Suspended for a meditation', kind: 'runtime_error' code: 'delay_lama_detected' else c.outPorts.saved.send true c.outPorts.saved.disconnect() c.outPorts.add 'saved', datatype: 'boolean' c.outPorts.add 'error', datatype: 'object' form = new noflo.internalSocket.createSocket() saved = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.form.attach form c.outPorts.saved.attach saved c.outPorts.error.attach err noflo.helpers.MultiError c it 'should support multiple customized error messages', (done) -> errCount = 0 err.on 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'form_error' errCount++ err.on 'disconnect', -> chai.expect(errCount).to.equal 3 done() form.send name: 'PI:NAME:<NAME>END_PI' email: 'missing' form.disconnect() it 'should pass if everything is correct', (done) -> hadData = false saved.removeAllListeners() saved.once 'data', (data) -> chai.expect(data).to.be.true hadData = true saved.once 'disconnect', -> chai.expect(hadData).to.be.true done() err.removeAllListeners() err.on 'data', (data) -> done data form.send name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' accept: true form.disconnect() it 'should handle fatals and runtimes normally', (done) -> saved.once 'data', (data) -> chai.expect(data).to.be.false err.removeAllListeners() errCount = 0 err.once 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'runtime_error' errCount++ err.once 'disconnect', -> chai.expect(errCount).to.equal 1 done() form.send name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' accept: true form.disconnect() describe 'with async processes and groups', -> c = new noflo.Component c.inPorts.add 'form', datatype: 'object' c.outPorts.add 'saved', datatype: 'boolean' c.outPorts.add 'error', datatype: 'object' form = new noflo.internalSocket.createSocket() saved = new noflo.internalSocket.createSocket() err = new noflo.internalSocket.createSocket() c.inPorts.form.attach form c.outPorts.saved.attach saved c.outPorts.error.attach err noflo.helpers.WirePattern c, in: 'form' out: 'saved' async: true forwardGroups: true name: 'Registration' , (payload, groups, out, callback) -> # Validate form unless payload.name and payload.name.match /^\w{3,16}$/ this.error noflo.helpers.CustomError('Incorrect name', kind: 'form_error' code: 'invalid_name' param: 'name' ), ['e1'] unless payload.email and payload.email.match /^\w+@\w+\.\w+$/ this.error noflo.helpers.CustomError('Incorrect email', kind: 'form_error' code: 'invalid_email' param: 'email' ), ['e2'] unless payload.accept this.error noflo.helpers.CustomError('Terms have to be accepted', kind: 'form_error' code: 'terms_not_accepted' param: 'accept' ), ['e3'] # Finish validation return callback no if this.hasErrors setTimeout -> # Emulating some processing logic here if payload.name is 'DelayLama' # oops out.send false return callback noflo.helpers.CustomError 'Suspended for a meditation', kind: 'runtime_error' code: 'delay_lama_detected' else out.send true callback() , 10 it 'should support multiple error messages and groups and scope', (done) -> expected = [ 'Registration' 'async0' 'e1' 'async0' 'e2' 'async0' 'e3' ] actual = [] errCount = 0 brackets = 0 err.on 'ip', (ip) -> chai.expect(ip.scope).to.equal 'foo' if ip.type is 'openBracket' brackets++ return actual.push ip.data if ip.type is 'data' data = ip.data chai.expect(data).to.be.an.error chai.expect(data.kind).to.equal 'form_error' errCount++ if ip.type is 'closeBracket' brackets-- if brackets is 0 chai.expect(errCount).to.equal 3 chai.expect(actual).to.deep.equal expected done() form.post new noflo.IP 'openBracket', 'async0', scope: 'foo' form.post new noflo.IP 'data', name: 'PI:NAME:<NAME>END_PI' email: 'missing' , scope: 'foo' form.post new noflo.IP 'closeBracket', 'async0', scope: 'foo' # form.disconnect() it 'should pass if everything is correct', (done) -> hadData = false saved.removeAllListeners() saved.once 'data', (data) -> chai.expect(data).to.be.true hadData = true saved.once 'disconnect', -> chai.expect(hadData).to.be.true done() err.removeAllListeners() err.on 'data', (data) -> done data form.send name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' accept: true form.disconnect() it 'should handle fatals and runtimes normally', (done) -> saved.once 'data', (data) -> chai.expect(data).to.be.false err.removeAllListeners() errCount = 0 grpCount = 0 err.on 'begingroup', (grp) -> chai.expect(grp).to.equal 'Registration' grpCount++ err.once 'data', (data) -> chai.expect(data instanceof Error).to.be.true chai.expect(data.kind).to.equal 'runtime_error' errCount++ err.once 'disconnect', -> chai.expect(errCount).to.equal 1 chai.expect(grpCount).to.equal 1 done() form.send name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' accept: true form.disconnect() it 'should reset state if component is shut down', (done) -> c2 = new noflo.Component c2.inPorts.add 'name', datatype: 'string' handle: (ip) -> return unless ip.type is 'data' c2.error new Error "The name will never pass!" noflo.helpers.MultiError c2 ins = new noflo.internalSocket.createSocket() c2.inPorts.name.attach ins ins.send 'PI:NAME:<NAME>END_PI' chai.expect(c2.hasErrors).to.be.true chai.expect(c2.errors).to.be.an 'array' chai.expect(c2.errors).to.have.lengthOf 1 c2.shutdown() chai.expect(c2.hasErrors).to.be.false chai.expect(c2.errors).to.be.an 'array' chai.expect(c2.errors).to.have.lengthOf 0 done()
[ { "context": "### Copyright (c) 2015 Magnus Leo. All rights reserved. ###\n\nutil = require('./util", "end": 33, "score": 0.9998658299446106, "start": 23, "tag": "NAME", "value": "Magnus Leo" }, { "context": " if typeof key is 'string'\n key = keyCodes[key.toUpperCase()]\n if event.pressedKeys.in", "end": 595, "score": 0.6172522902488708, "start": 589, "tag": "KEY", "value": "Codes[" }, { "context": "eof key is 'string'\n key = keyCodes[key.toUpperCase()]\n if event.pressedKeys.indexOf(key) > -1\n ", "end": 613, "score": 0.8474624752998352, "start": 599, "tag": "KEY", "value": "toUpperCase()]" }, { "context": "of key is 'string'\n key = keyCodes[key.toUpperCase()]\n if event.pressedKeys.indexOf(key) == -", "end": 909, "score": 0.8301462531089783, "start": 898, "tag": "KEY", "value": "toUpperCase" } ]
src/modules/io.coffee
magnusleo/Leo-Engine
1
### Copyright (c) 2015 Magnus Leo. All rights reserved. ### util = require('./util') event = require('./event') io = {} module.exports = io io.getPressedKeys = -> return event.pressedKeys io.isKeyPressed = (key) -> if typeof key is 'string' key = util.KEY_CODES[key.toUpperCase()] unless typeof key is 'number' return false return event.pressedKeys.indexOf(key) > -1 io.anyKeyPressed = (keys) -> keyCodes = util.KEY_CODES if typeof key is 'string' key = [key] for key in keys if typeof key is 'string' key = keyCodes[key.toUpperCase()] if event.pressedKeys.indexOf(key) > -1 return true return false io.allKeysPressed = (keys) -> keyCodes = util.KEY_CODES if typeof key is 'string' key = [key] for key in keys if typeof key is 'string' key = keyCodes[key.toUpperCase()] if event.pressedKeys.indexOf(key) == -1 return false return true
181861
### Copyright (c) 2015 <NAME>. All rights reserved. ### util = require('./util') event = require('./event') io = {} module.exports = io io.getPressedKeys = -> return event.pressedKeys io.isKeyPressed = (key) -> if typeof key is 'string' key = util.KEY_CODES[key.toUpperCase()] unless typeof key is 'number' return false return event.pressedKeys.indexOf(key) > -1 io.anyKeyPressed = (keys) -> keyCodes = util.KEY_CODES if typeof key is 'string' key = [key] for key in keys if typeof key is 'string' key = key<KEY>key.<KEY> if event.pressedKeys.indexOf(key) > -1 return true return false io.allKeysPressed = (keys) -> keyCodes = util.KEY_CODES if typeof key is 'string' key = [key] for key in keys if typeof key is 'string' key = keyCodes[key.<KEY>()] if event.pressedKeys.indexOf(key) == -1 return false return true
true
### Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. ### util = require('./util') event = require('./event') io = {} module.exports = io io.getPressedKeys = -> return event.pressedKeys io.isKeyPressed = (key) -> if typeof key is 'string' key = util.KEY_CODES[key.toUpperCase()] unless typeof key is 'number' return false return event.pressedKeys.indexOf(key) > -1 io.anyKeyPressed = (keys) -> keyCodes = util.KEY_CODES if typeof key is 'string' key = [key] for key in keys if typeof key is 'string' key = keyPI:KEY:<KEY>END_PIkey.PI:KEY:<KEY>END_PI if event.pressedKeys.indexOf(key) > -1 return true return false io.allKeysPressed = (keys) -> keyCodes = util.KEY_CODES if typeof key is 'string' key = [key] for key in keys if typeof key is 'string' key = keyCodes[key.PI:KEY:<KEY>END_PI()] if event.pressedKeys.indexOf(key) == -1 return false return true
[ { "context": "nv.MONGO_GUSHITIE_URL || 'mongodb://hotShareAdmin:aei_19056@host1.tiegushi.com:27017/hotShare'\n\n GushitieDB = new MongoInternal", "end": 121, "score": 0.9999281764030457, "start": 93, "tag": "EMAIL", "value": "aei_19056@host1.tiegushi.com" }, { "context": "ollection(\"viewers\", { _driver: GushitieDB })\n @GushitiePosts = new Mongo.Collection(\"posts\", { _driver:", "end": 293, "score": 0.595151424407959, "start": 288, "tag": "USERNAME", "value": "ushit" } ]
rocketchat/server/methods/gushitieMethods.coffee
Ritesh1991/mobile_app_server
0
Meteor.startup ()-> mongourl = process.env.MONGO_GUSHITIE_URL || 'mongodb://hotShareAdmin:aei_19056@host1.tiegushi.com:27017/hotShare' GushitieDB = new MongoInternals.RemoteCollectionDriver(mongourl) @GushitieViewers = new Mongo.Collection("viewers", { _driver: GushitieDB }) @GushitiePosts = new Mongo.Collection("posts", { _driver: GushitieDB }) @GushitieMeets = new Mongo.Collection("meets", { _driver: GushitieDB }) @GushitieFeeds = new Mongo.Collection("feeds", { _driver: GushitieDB }) @GushitieFollower = new Mongo.Collection("follower", { _driver: GushitieDB }) Meteor.methods 'getMyState':(gUserID,skip,limit)-> this.unblock() unless skip skip = 0 unless limit limit = 20 console.log('This is '+gUserID) #result = Neo4j.query "MATCH (u:User)-[v:VIEWER]->(p:Post) WHERE u.userId=\"#{gUserID}\" RETURN v.by,p ORDER BY v.by DESC SKIP #{skip} LIMIT #{limit}" #console.log result #viewers = GushitieViewers.find({userId:'eWMF3NWh6Wpc9zfnt'}, {sort: {createdAt: -1}, limit: 5,skip:0}) viewers = GushitieViewers.find({userId:gUserID}, {sort: {createdAt: 1}, limit: limit,skip:skip,fields:{postId:1,createdAt:1}}) readList = [] viewers.forEach((a)-> #console.log(a) item=[a.createdAt] postDetail=GushitiePosts.findOne({_id:a.postId},fields:{mainImage:1,ownerName:1,title:1,addontitle:1,createdAt:1}) if postDetail postDetail.postId=a.postId postDetail.name=postDetail.title delete postDetail['_id'] delete postDetail['title'] item.push postDetail console.log postDetail readList.push item ) return { 'list': readList } 'getSocialState':(gUserID)-> this.unblock() meet=GushitieMeets.find({me:gUserID},{sort:{createdAt:-1},limit:5}).fetch() result=[] meet.forEach((a)-> console.log(a.ta) if a and a.ta userInfo=GushitieUsers.findOne({_id:a.ta},{fields:{username:1,'profile.fullname':1,username:1,'profile.location':1}}) if userInfo if userInfo.profile and userInfo.profile.fullname and userInfo.profile.fullname isnt '' name = userInfo.profile.fullname else name = userInfo.fullname if userInfo.profile and userInfo.profile.location and userInfo.profile.location isnt '' location = userInfo.profile.location else location = null if name if location result.push({name:name,location:location}) else result.push({name:name}) ) console.log result return result 'getPostInfo':(postId)-> this.unblock() postinfo = GushitiePosts.findOne({_id:postId},{fields:{mainImage:1,owner:1,ownerName:1,title:1,addontitle:1,createdAt:1,isReview:1,publish:1}}) return postinfo 'getMyPostStat': (postId)-> this.unblock() me=Meteor.user() myGushitieID=null if me and me.services and me.services.gushitie and me.services.gushitie.id myGushitieID=me.services.gushitie.id if me and me.gushitie and me.gushitie.id myGushitieID=me.gushitie.id console.log myGushitieID stat = {} if myGushitieID? postinfo = GushitiePosts.findOne({_id:postId},{fields:{browse:1}}) console.log(postinfo) if postinfo and postinfo.browse stat.browses = postinfo.browse #GushitieViewers.find({postId: postId}).count() readers=GushitieViewers.find({postId: postId},{sort:{createdBy:-1},limit:5,fields:{username:1,userId:1}}).fetch() console.log(readers) readerList=[] readers=readers.forEach((item,index)-> if item.userId and item.userId is myGushitieID return if item.username readerList.push(item.username) return ) stat.readers=readerList stat.posts = GushitiePosts.find({owner: myGushitieID}).count() #stat.totalbrowses = 0 stat.locations = [] postIds = [] readerIds = [] ### GushitiePosts.find({owner: myGushitieID}).forEach((post) -> postIds.push(post._id) ) if postIds.length > 0 GushitieViewers.find({postId: {$in: postIds}}).forEach((viewer) -> if !~readerIds.indexOf(viewer.userId) readerIds.push(viewer.userId) ) if readerIds.length > 0 stat.totalbrowses = readerIds.length GushitieUsersInner.find({_id: {$in: readerIds}}).forEach((user)-> if user.profile and user.profile.location if !~stat.locations.indexOf(user.profile.location) and stat.locations.length < 5 console.log('>>>>: ', user.profile.location) stat.locations.push(user.profile.location) ) GushitieUsers.find({_id: {$in: readerIds}}).each((err, user)-> if user.profile and user.profile.location if !~stat.locations.indexOf(user.profile.location) and stat.locations.length < 5 stat.locations.push(user.profile.location) ) ### return stat 'calcRelationship':(userId)-> this.unblock() resp={} me=Meteor.user() taGushitieId=null myGushitieID=null if me and me.services and me.services.gushitie and me.services.gushitie.id myGushitieID=me.services.gushitie.id else if me and me.gushitie and me.gushitie.id myGushitieID=me.gushitie.id ta=Meteor.users.findOne({_id:userId}) resp.taId=ta._id resp.taName=ta.name if ta and ta.services and ta.services.gushitie and ta.services.gushitie.id taGushitieId=ta.services.gushitie.id else if ta and ta.gushitie and ta.gushitie.id taGushitieId=ta.gushitie.id if taGushitieId and myGushitieID #Calc the meet time mutualPosts = Neo4j.query "MATCH (fromUser:User)-[v:VIEWER]->(p:Post)-[v2:VIEWER]-(toUser:User) WHERE fromUser.userId=\"#{myGushitieID}\" AND toUser.userId=\"#{taGushitieId}\" RETURN DISTINCT p ORDER BY p.createdBy DESC LIMIT 5" meetTimes = mutualPosts.length console.log('Meet time '+meetTimes) #resp.meets = meetTimes if meetTimes > 0 #Calc the mutual post resp.mutualPosts = mutualPosts console.log('get mutualPosts list') console.log(mutualPosts) else #Calc the post not read but read by ta queryString="MATCH (u:User)-[v:VIEWER]->(p:Post),(u1:User)-[v1:VIEWER]->(p1:Post) WHERE u.userId=\"#{myGushitieID}\" AND u1.userId=\"#{taGushitieId}\" AND p.postId<>p1.postId RETURN p1 ORDER BY p1.createdBy DESC LIMIT 5" taRead=Neo4j.query queryString resp.taRead = taRead #console.log(queryString) #console.log(resp.taRead ) return resp else console.log('User '+userId+' dont have guishitie id') return {} #console.log(Meteor.user())
22066
Meteor.startup ()-> mongourl = process.env.MONGO_GUSHITIE_URL || 'mongodb://hotShareAdmin:<EMAIL>:27017/hotShare' GushitieDB = new MongoInternals.RemoteCollectionDriver(mongourl) @GushitieViewers = new Mongo.Collection("viewers", { _driver: GushitieDB }) @GushitiePosts = new Mongo.Collection("posts", { _driver: GushitieDB }) @GushitieMeets = new Mongo.Collection("meets", { _driver: GushitieDB }) @GushitieFeeds = new Mongo.Collection("feeds", { _driver: GushitieDB }) @GushitieFollower = new Mongo.Collection("follower", { _driver: GushitieDB }) Meteor.methods 'getMyState':(gUserID,skip,limit)-> this.unblock() unless skip skip = 0 unless limit limit = 20 console.log('This is '+gUserID) #result = Neo4j.query "MATCH (u:User)-[v:VIEWER]->(p:Post) WHERE u.userId=\"#{gUserID}\" RETURN v.by,p ORDER BY v.by DESC SKIP #{skip} LIMIT #{limit}" #console.log result #viewers = GushitieViewers.find({userId:'eWMF3NWh6Wpc9zfnt'}, {sort: {createdAt: -1}, limit: 5,skip:0}) viewers = GushitieViewers.find({userId:gUserID}, {sort: {createdAt: 1}, limit: limit,skip:skip,fields:{postId:1,createdAt:1}}) readList = [] viewers.forEach((a)-> #console.log(a) item=[a.createdAt] postDetail=GushitiePosts.findOne({_id:a.postId},fields:{mainImage:1,ownerName:1,title:1,addontitle:1,createdAt:1}) if postDetail postDetail.postId=a.postId postDetail.name=postDetail.title delete postDetail['_id'] delete postDetail['title'] item.push postDetail console.log postDetail readList.push item ) return { 'list': readList } 'getSocialState':(gUserID)-> this.unblock() meet=GushitieMeets.find({me:gUserID},{sort:{createdAt:-1},limit:5}).fetch() result=[] meet.forEach((a)-> console.log(a.ta) if a and a.ta userInfo=GushitieUsers.findOne({_id:a.ta},{fields:{username:1,'profile.fullname':1,username:1,'profile.location':1}}) if userInfo if userInfo.profile and userInfo.profile.fullname and userInfo.profile.fullname isnt '' name = userInfo.profile.fullname else name = userInfo.fullname if userInfo.profile and userInfo.profile.location and userInfo.profile.location isnt '' location = userInfo.profile.location else location = null if name if location result.push({name:name,location:location}) else result.push({name:name}) ) console.log result return result 'getPostInfo':(postId)-> this.unblock() postinfo = GushitiePosts.findOne({_id:postId},{fields:{mainImage:1,owner:1,ownerName:1,title:1,addontitle:1,createdAt:1,isReview:1,publish:1}}) return postinfo 'getMyPostStat': (postId)-> this.unblock() me=Meteor.user() myGushitieID=null if me and me.services and me.services.gushitie and me.services.gushitie.id myGushitieID=me.services.gushitie.id if me and me.gushitie and me.gushitie.id myGushitieID=me.gushitie.id console.log myGushitieID stat = {} if myGushitieID? postinfo = GushitiePosts.findOne({_id:postId},{fields:{browse:1}}) console.log(postinfo) if postinfo and postinfo.browse stat.browses = postinfo.browse #GushitieViewers.find({postId: postId}).count() readers=GushitieViewers.find({postId: postId},{sort:{createdBy:-1},limit:5,fields:{username:1,userId:1}}).fetch() console.log(readers) readerList=[] readers=readers.forEach((item,index)-> if item.userId and item.userId is myGushitieID return if item.username readerList.push(item.username) return ) stat.readers=readerList stat.posts = GushitiePosts.find({owner: myGushitieID}).count() #stat.totalbrowses = 0 stat.locations = [] postIds = [] readerIds = [] ### GushitiePosts.find({owner: myGushitieID}).forEach((post) -> postIds.push(post._id) ) if postIds.length > 0 GushitieViewers.find({postId: {$in: postIds}}).forEach((viewer) -> if !~readerIds.indexOf(viewer.userId) readerIds.push(viewer.userId) ) if readerIds.length > 0 stat.totalbrowses = readerIds.length GushitieUsersInner.find({_id: {$in: readerIds}}).forEach((user)-> if user.profile and user.profile.location if !~stat.locations.indexOf(user.profile.location) and stat.locations.length < 5 console.log('>>>>: ', user.profile.location) stat.locations.push(user.profile.location) ) GushitieUsers.find({_id: {$in: readerIds}}).each((err, user)-> if user.profile and user.profile.location if !~stat.locations.indexOf(user.profile.location) and stat.locations.length < 5 stat.locations.push(user.profile.location) ) ### return stat 'calcRelationship':(userId)-> this.unblock() resp={} me=Meteor.user() taGushitieId=null myGushitieID=null if me and me.services and me.services.gushitie and me.services.gushitie.id myGushitieID=me.services.gushitie.id else if me and me.gushitie and me.gushitie.id myGushitieID=me.gushitie.id ta=Meteor.users.findOne({_id:userId}) resp.taId=ta._id resp.taName=ta.name if ta and ta.services and ta.services.gushitie and ta.services.gushitie.id taGushitieId=ta.services.gushitie.id else if ta and ta.gushitie and ta.gushitie.id taGushitieId=ta.gushitie.id if taGushitieId and myGushitieID #Calc the meet time mutualPosts = Neo4j.query "MATCH (fromUser:User)-[v:VIEWER]->(p:Post)-[v2:VIEWER]-(toUser:User) WHERE fromUser.userId=\"#{myGushitieID}\" AND toUser.userId=\"#{taGushitieId}\" RETURN DISTINCT p ORDER BY p.createdBy DESC LIMIT 5" meetTimes = mutualPosts.length console.log('Meet time '+meetTimes) #resp.meets = meetTimes if meetTimes > 0 #Calc the mutual post resp.mutualPosts = mutualPosts console.log('get mutualPosts list') console.log(mutualPosts) else #Calc the post not read but read by ta queryString="MATCH (u:User)-[v:VIEWER]->(p:Post),(u1:User)-[v1:VIEWER]->(p1:Post) WHERE u.userId=\"#{myGushitieID}\" AND u1.userId=\"#{taGushitieId}\" AND p.postId<>p1.postId RETURN p1 ORDER BY p1.createdBy DESC LIMIT 5" taRead=Neo4j.query queryString resp.taRead = taRead #console.log(queryString) #console.log(resp.taRead ) return resp else console.log('User '+userId+' dont have guishitie id') return {} #console.log(Meteor.user())
true
Meteor.startup ()-> mongourl = process.env.MONGO_GUSHITIE_URL || 'mongodb://hotShareAdmin:PI:EMAIL:<EMAIL>END_PI:27017/hotShare' GushitieDB = new MongoInternals.RemoteCollectionDriver(mongourl) @GushitieViewers = new Mongo.Collection("viewers", { _driver: GushitieDB }) @GushitiePosts = new Mongo.Collection("posts", { _driver: GushitieDB }) @GushitieMeets = new Mongo.Collection("meets", { _driver: GushitieDB }) @GushitieFeeds = new Mongo.Collection("feeds", { _driver: GushitieDB }) @GushitieFollower = new Mongo.Collection("follower", { _driver: GushitieDB }) Meteor.methods 'getMyState':(gUserID,skip,limit)-> this.unblock() unless skip skip = 0 unless limit limit = 20 console.log('This is '+gUserID) #result = Neo4j.query "MATCH (u:User)-[v:VIEWER]->(p:Post) WHERE u.userId=\"#{gUserID}\" RETURN v.by,p ORDER BY v.by DESC SKIP #{skip} LIMIT #{limit}" #console.log result #viewers = GushitieViewers.find({userId:'eWMF3NWh6Wpc9zfnt'}, {sort: {createdAt: -1}, limit: 5,skip:0}) viewers = GushitieViewers.find({userId:gUserID}, {sort: {createdAt: 1}, limit: limit,skip:skip,fields:{postId:1,createdAt:1}}) readList = [] viewers.forEach((a)-> #console.log(a) item=[a.createdAt] postDetail=GushitiePosts.findOne({_id:a.postId},fields:{mainImage:1,ownerName:1,title:1,addontitle:1,createdAt:1}) if postDetail postDetail.postId=a.postId postDetail.name=postDetail.title delete postDetail['_id'] delete postDetail['title'] item.push postDetail console.log postDetail readList.push item ) return { 'list': readList } 'getSocialState':(gUserID)-> this.unblock() meet=GushitieMeets.find({me:gUserID},{sort:{createdAt:-1},limit:5}).fetch() result=[] meet.forEach((a)-> console.log(a.ta) if a and a.ta userInfo=GushitieUsers.findOne({_id:a.ta},{fields:{username:1,'profile.fullname':1,username:1,'profile.location':1}}) if userInfo if userInfo.profile and userInfo.profile.fullname and userInfo.profile.fullname isnt '' name = userInfo.profile.fullname else name = userInfo.fullname if userInfo.profile and userInfo.profile.location and userInfo.profile.location isnt '' location = userInfo.profile.location else location = null if name if location result.push({name:name,location:location}) else result.push({name:name}) ) console.log result return result 'getPostInfo':(postId)-> this.unblock() postinfo = GushitiePosts.findOne({_id:postId},{fields:{mainImage:1,owner:1,ownerName:1,title:1,addontitle:1,createdAt:1,isReview:1,publish:1}}) return postinfo 'getMyPostStat': (postId)-> this.unblock() me=Meteor.user() myGushitieID=null if me and me.services and me.services.gushitie and me.services.gushitie.id myGushitieID=me.services.gushitie.id if me and me.gushitie and me.gushitie.id myGushitieID=me.gushitie.id console.log myGushitieID stat = {} if myGushitieID? postinfo = GushitiePosts.findOne({_id:postId},{fields:{browse:1}}) console.log(postinfo) if postinfo and postinfo.browse stat.browses = postinfo.browse #GushitieViewers.find({postId: postId}).count() readers=GushitieViewers.find({postId: postId},{sort:{createdBy:-1},limit:5,fields:{username:1,userId:1}}).fetch() console.log(readers) readerList=[] readers=readers.forEach((item,index)-> if item.userId and item.userId is myGushitieID return if item.username readerList.push(item.username) return ) stat.readers=readerList stat.posts = GushitiePosts.find({owner: myGushitieID}).count() #stat.totalbrowses = 0 stat.locations = [] postIds = [] readerIds = [] ### GushitiePosts.find({owner: myGushitieID}).forEach((post) -> postIds.push(post._id) ) if postIds.length > 0 GushitieViewers.find({postId: {$in: postIds}}).forEach((viewer) -> if !~readerIds.indexOf(viewer.userId) readerIds.push(viewer.userId) ) if readerIds.length > 0 stat.totalbrowses = readerIds.length GushitieUsersInner.find({_id: {$in: readerIds}}).forEach((user)-> if user.profile and user.profile.location if !~stat.locations.indexOf(user.profile.location) and stat.locations.length < 5 console.log('>>>>: ', user.profile.location) stat.locations.push(user.profile.location) ) GushitieUsers.find({_id: {$in: readerIds}}).each((err, user)-> if user.profile and user.profile.location if !~stat.locations.indexOf(user.profile.location) and stat.locations.length < 5 stat.locations.push(user.profile.location) ) ### return stat 'calcRelationship':(userId)-> this.unblock() resp={} me=Meteor.user() taGushitieId=null myGushitieID=null if me and me.services and me.services.gushitie and me.services.gushitie.id myGushitieID=me.services.gushitie.id else if me and me.gushitie and me.gushitie.id myGushitieID=me.gushitie.id ta=Meteor.users.findOne({_id:userId}) resp.taId=ta._id resp.taName=ta.name if ta and ta.services and ta.services.gushitie and ta.services.gushitie.id taGushitieId=ta.services.gushitie.id else if ta and ta.gushitie and ta.gushitie.id taGushitieId=ta.gushitie.id if taGushitieId and myGushitieID #Calc the meet time mutualPosts = Neo4j.query "MATCH (fromUser:User)-[v:VIEWER]->(p:Post)-[v2:VIEWER]-(toUser:User) WHERE fromUser.userId=\"#{myGushitieID}\" AND toUser.userId=\"#{taGushitieId}\" RETURN DISTINCT p ORDER BY p.createdBy DESC LIMIT 5" meetTimes = mutualPosts.length console.log('Meet time '+meetTimes) #resp.meets = meetTimes if meetTimes > 0 #Calc the mutual post resp.mutualPosts = mutualPosts console.log('get mutualPosts list') console.log(mutualPosts) else #Calc the post not read but read by ta queryString="MATCH (u:User)-[v:VIEWER]->(p:Post),(u1:User)-[v1:VIEWER]->(p1:Post) WHERE u.userId=\"#{myGushitieID}\" AND u1.userId=\"#{taGushitieId}\" AND p.postId<>p1.postId RETURN p1 ORDER BY p1.createdBy DESC LIMIT 5" taRead=Neo4j.query queryString resp.taRead = taRead #console.log(queryString) #console.log(resp.taRead ) return resp else console.log('User '+userId+' dont have guishitie id') return {} #console.log(Meteor.user())
[ { "context": " scope._store, \"create\"\n scope.create name: \"Lance\"\n expect(scope._store.create).toHaveBeenCall", "end": 552, "score": 0.9994379281997681, "start": 547, "tag": "NAME", "value": "Lance" }, { "context": "scope._store.create).toHaveBeenCalledWith {name: \"Lance\"}, {}, undefined\n \n test '#serializeAtt", "end": 622, "score": 0.9996647834777832, "start": 617, "tag": "NAME", "value": "Lance" }, { "context": "sForCreate', (done) ->\n _attributes = name: \"Joe\"\n _options = {}\n attributes = scope", "end": 731, "score": 0.9996288418769836, "start": 728, "tag": "NAME", "value": "Joe" }, { "context": "s)\n \n expect(attributes).toEqual name: \"Joe\"\n \n describe '#update', ->\n test '#seria", "end": 941, "score": 0.9996222257614136, "start": 938, "tag": "NAME", "value": "Joe" }, { "context": " scope._store.serializeAttributesForUpdate(name: \"John\", $pushAll: tags: [\"a\", \"b\"])\n query ", "end": 1087, "score": 0.9998565912246704, "start": 1083, "tag": "NAME", "value": "John" }, { "context": " \n expect(updates).toEqual \"$set\": { name: \"John\" }, \"$pushAll\": { tags : [ 'a', 'b' ] }\n exp", "end": 1248, "score": 0.9998489022254944, "start": 1244, "tag": "NAME", "value": "John" } ]
test/cases/store/mongodbTest.coffee
ludicast/tower
1
### require '../../config' scope = null user = null quit = false ini = false describe 'Tower.Store.MongoDB', -> beforeEach -> User.store(new Tower.Store.MongoDB(name: "users", type: "User")) #User.store.database.close() if User.store.database #Tower.Store.MongoDB.initialize() scope = User afterEach -> scope._store.constructor.database.close() if quit scope = null describe '#create', -> test 'with attributes', (done) -> spyOn scope._store, "create" scope.create name: "Lance" expect(scope._store.create).toHaveBeenCalledWith {name: "Lance"}, {}, undefined test '#serializeAttributesForCreate', (done) -> _attributes = name: "Joe" _options = {} attributes = scope._store.serializeAttributesForCreate(_attributes) options = scope._store.serializeOptions(_options) expect(attributes).toEqual name: "Joe" describe '#update', -> test '#serializing', (done) -> updates = scope._store.serializeAttributesForUpdate(name: "John", $pushAll: tags: ["a", "b"]) query = scope._store.serializeQuery(id: $in: [1, 2, 3]) expect(updates).toEqual "$set": { name: "John" }, "$pushAll": { tags : [ 'a', 'b' ] } expect(query).toEqual _id: $in: [1, 2, 3] done() test '{ $push : { field : value }', (done) -> updates = scope._store.serializeAttributesForUpdate($push: tags: ["a"]) expect(updates).toEqual $push: tags: ["a"] done() test '{ $inc : { field : value } }' test '{ $set : { field : value } }' test '{ $unset : { field : 1} }' test '{ $push : { field : value } }' test '{ $pushAll : { field : valueArray } }' test '{ $addToSet : { field : value } }' test '{ $pop : { field : 1 } }' test '{ $pop : { field : -1 } }' test '{ $pull : { field : _value } }' test '{ $pullAll : { field : value_array } }' ###
111918
### require '../../config' scope = null user = null quit = false ini = false describe 'Tower.Store.MongoDB', -> beforeEach -> User.store(new Tower.Store.MongoDB(name: "users", type: "User")) #User.store.database.close() if User.store.database #Tower.Store.MongoDB.initialize() scope = User afterEach -> scope._store.constructor.database.close() if quit scope = null describe '#create', -> test 'with attributes', (done) -> spyOn scope._store, "create" scope.create name: "<NAME>" expect(scope._store.create).toHaveBeenCalledWith {name: "<NAME>"}, {}, undefined test '#serializeAttributesForCreate', (done) -> _attributes = name: "<NAME>" _options = {} attributes = scope._store.serializeAttributesForCreate(_attributes) options = scope._store.serializeOptions(_options) expect(attributes).toEqual name: "<NAME>" describe '#update', -> test '#serializing', (done) -> updates = scope._store.serializeAttributesForUpdate(name: "<NAME>", $pushAll: tags: ["a", "b"]) query = scope._store.serializeQuery(id: $in: [1, 2, 3]) expect(updates).toEqual "$set": { name: "<NAME>" }, "$pushAll": { tags : [ 'a', 'b' ] } expect(query).toEqual _id: $in: [1, 2, 3] done() test '{ $push : { field : value }', (done) -> updates = scope._store.serializeAttributesForUpdate($push: tags: ["a"]) expect(updates).toEqual $push: tags: ["a"] done() test '{ $inc : { field : value } }' test '{ $set : { field : value } }' test '{ $unset : { field : 1} }' test '{ $push : { field : value } }' test '{ $pushAll : { field : valueArray } }' test '{ $addToSet : { field : value } }' test '{ $pop : { field : 1 } }' test '{ $pop : { field : -1 } }' test '{ $pull : { field : _value } }' test '{ $pullAll : { field : value_array } }' ###
true
### require '../../config' scope = null user = null quit = false ini = false describe 'Tower.Store.MongoDB', -> beforeEach -> User.store(new Tower.Store.MongoDB(name: "users", type: "User")) #User.store.database.close() if User.store.database #Tower.Store.MongoDB.initialize() scope = User afterEach -> scope._store.constructor.database.close() if quit scope = null describe '#create', -> test 'with attributes', (done) -> spyOn scope._store, "create" scope.create name: "PI:NAME:<NAME>END_PI" expect(scope._store.create).toHaveBeenCalledWith {name: "PI:NAME:<NAME>END_PI"}, {}, undefined test '#serializeAttributesForCreate', (done) -> _attributes = name: "PI:NAME:<NAME>END_PI" _options = {} attributes = scope._store.serializeAttributesForCreate(_attributes) options = scope._store.serializeOptions(_options) expect(attributes).toEqual name: "PI:NAME:<NAME>END_PI" describe '#update', -> test '#serializing', (done) -> updates = scope._store.serializeAttributesForUpdate(name: "PI:NAME:<NAME>END_PI", $pushAll: tags: ["a", "b"]) query = scope._store.serializeQuery(id: $in: [1, 2, 3]) expect(updates).toEqual "$set": { name: "PI:NAME:<NAME>END_PI" }, "$pushAll": { tags : [ 'a', 'b' ] } expect(query).toEqual _id: $in: [1, 2, 3] done() test '{ $push : { field : value }', (done) -> updates = scope._store.serializeAttributesForUpdate($push: tags: ["a"]) expect(updates).toEqual $push: tags: ["a"] done() test '{ $inc : { field : value } }' test '{ $set : { field : value } }' test '{ $unset : { field : 1} }' test '{ $push : { field : value } }' test '{ $pushAll : { field : valueArray } }' test '{ $addToSet : { field : value } }' test '{ $pop : { field : 1 } }' test '{ $pop : { field : -1 } }' test '{ $pull : { field : _value } }' test '{ $pullAll : { field : value_array } }' ###
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9982690215110779, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-pipe-file-to-http.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. makeRequest = -> req = http.request( port: common.PORT path: "/" method: "POST" ) common.error "pipe!" s = fs.ReadStream(filename) s.pipe req s.on "data", (chunk) -> console.error "FS data chunk=%d", chunk.length return s.on "end", -> console.error "FS end" return s.on "close", (err) -> throw err if err clientReqComplete = true common.error "client finished sending request" return req.on "response", (res) -> console.error "RESPONSE", res.statusCode, res.headers res.resume() res.on "end", -> console.error "RESPONSE end" server.close() return return return common = require("../common") assert = require("assert") fs = require("fs") http = require("http") path = require("path") cp = require("child_process") filename = path.join(common.tmpDir or "/tmp", "big") clientReqComplete = false count = 0 server = http.createServer((req, res) -> console.error "SERVER request" timeoutId = undefined assert.equal "POST", req.method req.pause() common.error "request paused" setTimeout (-> req.resume() common.error "request resumed" return ), 1000 req.on "data", (chunk) -> common.error "recv data! nchars = " + chunk.length count += chunk.length return req.on "end", -> clearTimeout timeoutId if timeoutId console.log "request complete from server" res.writeHead 200, "Content-Type": "text/plain" res.end() return return ) server.listen common.PORT server.on "listening", -> cmd = common.ddCommand(filename, 10240) console.log "dd command: ", cmd cp.exec cmd, (err, stdout, stderr) -> throw err if err console.error "EXEC returned successfully stdout=%d stderr=%d", stdout.length, stderr.length makeRequest() return return process.on "exit", -> assert.equal 1024 * 10240, count assert.ok clientReqComplete return
175641
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. makeRequest = -> req = http.request( port: common.PORT path: "/" method: "POST" ) common.error "pipe!" s = fs.ReadStream(filename) s.pipe req s.on "data", (chunk) -> console.error "FS data chunk=%d", chunk.length return s.on "end", -> console.error "FS end" return s.on "close", (err) -> throw err if err clientReqComplete = true common.error "client finished sending request" return req.on "response", (res) -> console.error "RESPONSE", res.statusCode, res.headers res.resume() res.on "end", -> console.error "RESPONSE end" server.close() return return return common = require("../common") assert = require("assert") fs = require("fs") http = require("http") path = require("path") cp = require("child_process") filename = path.join(common.tmpDir or "/tmp", "big") clientReqComplete = false count = 0 server = http.createServer((req, res) -> console.error "SERVER request" timeoutId = undefined assert.equal "POST", req.method req.pause() common.error "request paused" setTimeout (-> req.resume() common.error "request resumed" return ), 1000 req.on "data", (chunk) -> common.error "recv data! nchars = " + chunk.length count += chunk.length return req.on "end", -> clearTimeout timeoutId if timeoutId console.log "request complete from server" res.writeHead 200, "Content-Type": "text/plain" res.end() return return ) server.listen common.PORT server.on "listening", -> cmd = common.ddCommand(filename, 10240) console.log "dd command: ", cmd cp.exec cmd, (err, stdout, stderr) -> throw err if err console.error "EXEC returned successfully stdout=%d stderr=%d", stdout.length, stderr.length makeRequest() return return process.on "exit", -> assert.equal 1024 * 10240, count assert.ok clientReqComplete return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. makeRequest = -> req = http.request( port: common.PORT path: "/" method: "POST" ) common.error "pipe!" s = fs.ReadStream(filename) s.pipe req s.on "data", (chunk) -> console.error "FS data chunk=%d", chunk.length return s.on "end", -> console.error "FS end" return s.on "close", (err) -> throw err if err clientReqComplete = true common.error "client finished sending request" return req.on "response", (res) -> console.error "RESPONSE", res.statusCode, res.headers res.resume() res.on "end", -> console.error "RESPONSE end" server.close() return return return common = require("../common") assert = require("assert") fs = require("fs") http = require("http") path = require("path") cp = require("child_process") filename = path.join(common.tmpDir or "/tmp", "big") clientReqComplete = false count = 0 server = http.createServer((req, res) -> console.error "SERVER request" timeoutId = undefined assert.equal "POST", req.method req.pause() common.error "request paused" setTimeout (-> req.resume() common.error "request resumed" return ), 1000 req.on "data", (chunk) -> common.error "recv data! nchars = " + chunk.length count += chunk.length return req.on "end", -> clearTimeout timeoutId if timeoutId console.log "request complete from server" res.writeHead 200, "Content-Type": "text/plain" res.end() return return ) server.listen common.PORT server.on "listening", -> cmd = common.ddCommand(filename, 10240) console.log "dd command: ", cmd cp.exec cmd, (err, stdout, stderr) -> throw err if err console.error "EXEC returned successfully stdout=%d stderr=%d", stdout.length, stderr.length makeRequest() return return process.on "exit", -> assert.equal 1024 * 10240, count assert.ok clientReqComplete return
[ { "context": "ata =\n domain: @config.domain\n userName: @config.userName\n password: @config.password\n database: ", "end": 19587, "score": 0.9797621965408325, "start": 19571, "tag": "USERNAME", "value": "@config.userName" }, { "context": "n\n userName: @config.userName\n password: @config.password\n database: @config.options.database\n se", "end": 19620, "score": 0.999213457107544, "start": 19604, "tag": "PASSWORD", "value": "@config.password" }, { "context": "ata =\n domain: @config.domain\n userName: @config.userName\n password: @config.password\n ", "end": 20184, "score": 0.8538365960121155, "start": 20184, "tag": "USERNAME", "value": "" }, { "context": " domain: @config.domain\n userName: @config.userName\n password: @config.password\n database: ", "end": 20201, "score": 0.7777762413024902, "start": 20193, "tag": "USERNAME", "value": "userName" }, { "context": "n\n userName: @config.userName\n password: @config.password\n database: @config.options.database\n ap", "end": 20234, "score": 0.999116063117981, "start": 20218, "tag": "PASSWORD", "value": "@config.password" } ]
src/connection.coffee
sgermain06/tedious-int64-native
0
require('./buffertools') BulkLoad = require('./bulk-load') Debug = require('./debug') EventEmitter = require('events').EventEmitter instanceLookup = require('./instance-lookup').instanceLookup TYPE = require('./packet').TYPE PreloginPayload = require('./prelogin-payload') Login7Payload = require('./login7-payload') NTLMResponsePayload = require('./ntlm-payload') Request = require('./request') RpcRequestPayload = require('./rpcrequest-payload') SqlBatchPayload = require('./sqlbatch-payload') MessageIO = require('./message-io') Socket = require('net').Socket TokenStreamParser = require('./token/token-stream-parser').Parser Transaction = require('./transaction').Transaction ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL crypto = require('crypto') tls = require('tls') {ConnectionError, RequestError} = require('./errors') # A rather basic state machine for managing a connection. # Implements something approximating s3.2.1. KEEP_ALIVE_INITIAL_DELAY = 30 * 1000 DEFAULT_CONNECT_TIMEOUT = 15 * 1000 DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000 DEFAULT_CANCEL_TIMEOUT = 5 * 1000 DEFAULT_PACKET_SIZE = 4 * 1024 DEFAULT_TEXTSIZE = '2147483647' DEFAULT_PORT = 1433 DEFAULT_TDS_VERSION = '7_4' class Connection extends EventEmitter STATE: CONNECTING: name: 'Connecting' enter: -> @initialiseConnection() events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) socketConnect: -> @sendPreLogin() @transitionTo(@STATE.SENT_PRELOGIN) SENT_PRELOGIN: name: 'SentPrelogin' enter: -> @emptyMessageBuffer() events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @addToMessageBuffer(data) message: -> @processPreLoginResponse() noTls: -> @sendLogin7Packet() if @config.domain @transitionTo(@STATE.SENT_LOGIN7_WITH_NTLM) else @transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN) tls: -> @initiateTlsSslHandshake() @sendLogin7Packet() @transitionTo(@STATE.SENT_TLSSSLNEGOTIATION) REROUTING: name: 'ReRouting' enter: -> @cleanupConnection(true) events: message: -> socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) reconnect: -> @config.server = @routingData.server @config.options.port = @routingData.port @transitionTo(@STATE.CONNECTING) SENT_TLSSSLNEGOTIATION: name: 'SentTLSSSLNegotiation' enter: -> @tlsNegotiationComplete = false events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @securePair.encrypted.write(data) tlsNegotiated: -> @tlsNegotiationComplete = true message: -> if @tlsNegotiationComplete @transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN) else SENT_LOGIN7_WITH_STANDARD_LOGIN: name: 'SentLogin7WithStandardLogin' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) loggedIn: -> @transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL) routingChange: -> @transitionTo(@STATE.REROUTING) loginFailed: -> @transitionTo(@STATE.FINAL) message: -> @processLogin7Response() SENT_LOGIN7_WITH_NTLM: name: 'SentLogin7WithNTLMLogin' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) receivedChallenge: -> @sendNTLMResponsePacket() @transitionTo(@STATE.SENT_NTLM_RESPONSE) loginFailed: -> @transitionTo(@STATE.FINAL) message: -> @processLogin7NTLMResponse() SENT_NTLM_RESPONSE: name: 'SentNTLMResponse' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) loggedIn: -> @transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL) loginFailed: -> @transitionTo(@STATE.FINAL) routingChange: -> @transitionTo(@STATE.REROUTING) message: -> @processLogin7NTLMAck() LOGGED_IN_SENDING_INITIAL_SQL: name: 'LoggedInSendingInitialSql' enter: -> @sendInitialSql() events: connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) message: (error) -> @transitionTo(@STATE.LOGGED_IN) @processedInitialSql() LOGGED_IN: name: 'LoggedIn' events: socketError: (error) -> @transitionTo(@STATE.FINAL) SENT_CLIENT_REQUEST: name: 'SentClientRequest' events: socketError: (error) -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) message: -> @clearRequestTimer() @transitionTo(@STATE.LOGGED_IN) sqlRequest = @request @request = undefined sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows) SENT_ATTENTION: name: 'SentAttention' enter: -> @attentionReceived = false events: socketError: (error) -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) attention: -> @attentionReceived = true message: -> # 3.2.5.7 Sent Attention State # Discard any data contained in the response, until we receive the attention response if @attentionReceived sqlRequest = @request @request = undefined @transitionTo(@STATE.LOGGED_IN) if sqlRequest.canceled sqlRequest.callback(RequestError("Canceled.", 'ECANCEL')) else message = "Timeout: Request failed to complete in #{@config.options.requestTimeout}ms" sqlRequest.callback(RequestError(message, 'ETIMEOUT')) FINAL: name: 'Final' enter: -> @cleanupConnection() events: loginFailed: -> # Do nothing. The connection was probably closed by the client code. connectTimeout: -> # Do nothing, as the timer should be cleaned up. message: -> # Do nothing socketError: -> # Do nothing constructor: (@config) -> @defaultConfig() @createDebug() @createTokenStreamParser() @inTransaction = false @transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])] @transitionTo(@STATE.CONNECTING) close: -> @transitionTo(@STATE.FINAL) initialiseConnection: -> @connect() @createConnectTimer() cleanupConnection: (@redirect)-> if !@closed @clearConnectTimer() @clearRequestTimer() @closeConnection() if !@redirect @emit('end') else @emit('rerouting') @closed = true @loggedIn = false @loginError = null defaultConfig: -> @config.options ||= {} @config.options.textsize ||= DEFAULT_TEXTSIZE @config.options.connectTimeout ||= DEFAULT_CONNECT_TIMEOUT @config.options.requestTimeout ?= DEFAULT_CLIENT_REQUEST_TIMEOUT @config.options.cancelTimeout ?= DEFAULT_CANCEL_TIMEOUT @config.options.packetSize ||= DEFAULT_PACKET_SIZE @config.options.tdsVersion ||= DEFAULT_TDS_VERSION @config.options.isolationLevel ||= ISOLATION_LEVEL.READ_COMMITTED @config.options.encrypt ||= false @config.options.cryptoCredentialsDetails ||= {} @config.options.useUTC ?= true @config.options.useColumnNames ?= false @config.options.connectionIsolationLevel ||= ISOLATION_LEVEL.READ_COMMITTED @config.options.readOnlyIntent ?= false @config.options.enableAnsiNullDefault ?= true if !@config.options.port && !@config.options.instanceName @config.options.port = DEFAULT_PORT else if @config.options.port && @config.options.instanceName throw new Error("Port and instanceName are mutually exclusive, but #{@config.options.port} and #{@config.options.instanceName} provided") else if @config.options.port if @config.options.port < 0 or @config.options.port > 65536 throw new RangeError "Port should be > 0 and < 65536" if @config.options.columnNameReplacer && typeof @config.options.columnNameReplacer != 'function' throw new TypeError('options.columnNameReplacer must be a function or null.') createDebug: -> @debug = new Debug(@config.options.debug) @debug.on('debug', (message) => @emit('debug', message) ) createTokenStreamParser: -> @tokenStreamParser = new TokenStreamParser(@debug, undefined, @config.options) @tokenStreamParser.on('infoMessage', (token) => @emit('infoMessage', token) ) @tokenStreamParser.on('sspichallenge', (token) => if token.ntlmpacket @ntlmpacket = token.ntlmpacket @emit('sspichallenge', token) ) @tokenStreamParser.on('errorMessage', (token) => @emit('errorMessage', token) if @loggedIn if @request @request.error = RequestError token.message, 'EREQUEST' @request.error.number = token.number @request.error.state = token.state @request.error.class = token.class @request.error.serverName = token.serverName @request.error.procName = token.procName @request.error.lineNumber = token.lineNumber else @loginError = ConnectionError token.message, 'ELOGIN' ) @tokenStreamParser.on('databaseChange', (token) => @emit('databaseChange', token.newValue) ) @tokenStreamParser.on('languageChange', (token) => @emit('languageChange', token.newValue) ) @tokenStreamParser.on('charsetChange', (token) => @emit('charsetChange', token.newValue) ) @tokenStreamParser.on('loginack', (token) => unless token.tdsVersion # unsupported TDS version @loginError = ConnectionError "Server responded with unknown TDS version.", 'ETDS' @loggedIn = false return unless token.interface # unsupported interface @loginError = ConnectionError "Server responded with unsupported interface.", 'EINTERFACENOTSUPP' @loggedIn = false return # use negotiated version @config.options.tdsVersion = token.tdsVersion @loggedIn = true ) @tokenStreamParser.on('routingChange', (token) => @routingData = token.newValue @dispatchEvent('routingChange') ) @tokenStreamParser.on('packetSizeChange', (token) => @messageIo.packetSize(token.newValue) ) # A new top-level transaction was started. This is not fired # for nested transactions. @tokenStreamParser.on('beginTransaction', (token) => @transactionDescriptors.push(token.newValue) @inTransaction = true ) # A top-level transaction was committed. This is not fired # for nested transactions. @tokenStreamParser.on('commitTransaction', (token) => @transactionDescriptors.length = 1 @inTransaction = false ) # A top-level transaction was rolled back. This is not fired # for nested transactions. This is also fired if a batch # aborting error happened that caused a rollback. @tokenStreamParser.on('rollbackTransaction', (token) => @transactionDescriptors.length = 1 # An outermost transaction was rolled back. Reset the transaction counter @inTransaction = false @emit('rollbackTransaction') ) @tokenStreamParser.on('columnMetadata', (token) => if @request if @config.options.useColumnNames columns = {} columns[col.colName] = col for col in token.columns when not columns[col.colName]? else columns = token.columns @request.emit('columnMetadata', columns) else @emit 'error', new Error "Received 'columnMetadata' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('order', (token) => if @request @request.emit('order', token.orderColumns) else @emit 'error', new Error "Received 'order' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('row', (token) => if @request if @config.options.rowCollectionOnRequestCompletion @request.rows.push token.columns if @config.options.rowCollectionOnDone @request.rst.push token.columns @request.emit('row', token.columns) else @emit 'error', new Error "Received 'row' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('returnStatus', (token) => if @request # Keep value for passing in 'doneProc' event. @procReturnStatusValue = token.value ) @tokenStreamParser.on('returnValue', (token) => if @request @request.emit('returnValue', token.paramName, token.value, token.metadata) ) @tokenStreamParser.on('doneProc', (token) => if @request @request.emit('doneProc', token.rowCount, token.more, @procReturnStatusValue, @request.rst) @procReturnStatusValue = undefined if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('doneInProc', (token) => if @request @request.emit('doneInProc', token.rowCount, token.more, @request.rst) if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('done', (token) => if @request if token.attention @dispatchEvent("attention") # check if the DONE_ERROR flags was set, but an ERROR token was not sent. if token.sqlError && !@request.error @request.error = RequestError('An unknown error has occurred.', 'UNKNOWN') @request.emit('done', token.rowCount, token.more, @request.rst) if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('resetConnection', (token) => @emit('resetConnection') ) @tokenStreamParser.on('tokenStreamError', (error) => @emit 'error', error @close() ) connect: -> if (@config.options.port) @connectOnPort(@config.options.port) else instanceLookup( @config.server @config.options.instanceName (message, port) => if @state == @STATE.FINAL return if message @emit('connect', ConnectionError(message, 'EINSTLOOKUP')) else @connectOnPort(port) @config.options.connectTimeout) connectOnPort: (port) -> @socket = new Socket({}) connectOpts = host: @config.server port: port if @config.options.localAddress connectOpts.localAddress = @config.options.localAddress @socket.connect(connectOpts) @socket.on('error', @socketError) @socket.on('connect', @socketConnect) @socket.on('close', @socketClose) @socket.on('end', @socketEnd) @messageIo = new MessageIO(@socket, @config.options.packetSize, @debug) @messageIo.on('data', (data) => @dispatchEvent('data', data) ) @messageIo.on('message', => @dispatchEvent('message') ) closeConnection: -> @socket?.destroy() createConnectTimer: -> @connectTimer = setTimeout(@connectTimeout, @config.options.connectTimeout) createRequestTimer: -> if @config.options.requestTimeout @requestTimer = setTimeout(@requestTimeout, @config.options.requestTimeout) connectTimeout: => message = "Failed to connect to #{@config.server}:#{@config.options.port} in #{@config.options.connectTimeout}ms" @debug.log(message) @emit('connect', ConnectionError(message, 'ETIMEOUT')) @connectTimer = undefined @dispatchEvent('connectTimeout') requestTimeout: => @requestTimer = undefined @messageIo.sendMessage(TYPE.ATTENTION) @transitionTo(@STATE.SENT_ATTENTION) clearConnectTimer: -> if @connectTimer clearTimeout(@connectTimer) clearRequestTimer: -> if @requestTimer clearTimeout(@requestTimer) transitionTo: (newState) -> if @state == newState @debug.log("State is already #{newState.name}") return if @state?.exit @state.exit.apply(@) @debug.log("State change: #{@state?.name} -> #{newState.name}") @state = newState if @state.enter @state.enter.apply(@) dispatchEvent: (eventName, args...) -> if @state?.events[eventName] eventFunction = @state.events[eventName].apply(@, args) else @emit 'error', new Error "No event '#{eventName}' in state '#{@state.name}'" @close() socketError: (error) => if @state == @STATE.CONNECTING message = "Failed to connect to #{@config.server}:#{@config.options.port} - #{error.message}" @debug.log(message) @emit('connect', ConnectionError(message, 'ESOCKET')) else message = "Connection lost - #{error.message}" @debug.log(message) @emit('error', ConnectionError(message, 'ESOCKET')) @dispatchEvent('socketError', error) socketConnect: => @socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY) @closed = false @debug.log("connected to #{@config.server}:#{@config.options.port}") @dispatchEvent('socketConnect') socketEnd: => @debug.log("socket ended") @transitionTo(@STATE.FINAL) socketClose: => @debug.log("connection to #{@config.server}:#{@config.options.port} closed") if @state is @STATE.REROUTING @debug.log("Rerouting to #{@routingData.server}:#{@routingData.port}") @dispatchEvent('reconnect') else @transitionTo(@STATE.FINAL) sendPreLogin: -> payload = new PreloginPayload({encrypt: @config.options.encrypt}) @messageIo.sendMessage(TYPE.PRELOGIN, payload.data) @debug.payload(-> payload.toString(' ') ) emptyMessageBuffer: -> @messageBuffer = new Buffer(0) addToMessageBuffer: (data) -> @messageBuffer = Buffer.concat([@messageBuffer, data]) processPreLoginResponse: -> preloginPayload = new PreloginPayload(@messageBuffer) @debug.payload(-> preloginPayload.toString(' ') ) if preloginPayload.encryptionString in ['ON','REQ'] @dispatchEvent('tls') else @dispatchEvent('noTls') sendLogin7Packet: -> loginData = domain: @config.domain userName: @config.userName password: @config.password database: @config.options.database serverName: @config.server appName: @config.options.appName packetSize: @config.options.packetSize tdsVersion: @config.options.tdsVersion initDbFatal: not @config.options.fallbackToDefaultDb readOnlyIntent: @config.options.readOnlyIntent payload = new Login7Payload(loginData) @messageIo.sendMessage(TYPE.LOGIN7, payload.data) @debug.payload(-> payload.toString(' ') ) sendNTLMResponsePacket: -> responseData = domain: @config.domain userName: @config.userName password: @config.password database: @config.options.database appName: @config.options.appName packetSize: @config.options.packetSize tdsVersion: @config.options.tdsVersion ntlmpacket: @ntlmpacket additional: @additional payload = new NTLMResponsePayload(responseData) @messageIo.sendMessage(TYPE.NTLMAUTH_PKT, payload.data) @debug.payload -> payload.toString ' ' initiateTlsSslHandshake: -> credentials = if tls.createSecureContext tls.createSecureContext(@config.options.cryptoCredentialsDetails) else crypto.createCredentials(@config.options.cryptoCredentialsDetails) @securePair = tls.createSecurePair(credentials) @securePair.on('secure', => cipher = @securePair.cleartext.getCipher() @debug.log("TLS negotiated (#{cipher.name}, #{cipher.version})") # console.log cipher # console.log @securePair.cleartext.getPeerCertificate() @emit('secure', @securePair.cleartext) @messageIo.encryptAllFutureTraffic() @dispatchEvent('tlsNegotiated') ) @securePair.encrypted.on('data', (data) => @messageIo.sendMessage(TYPE.PRELOGIN, data) ) @messageIo.tlsNegotiationStarting(@securePair) sendDataToTokenStreamParser: (data) -> @tokenStreamParser.addBuffer(data) sendInitialSql: -> payload = new SqlBatchPayload(@getInitialSql(), @currentTransactionDescriptor(), @config.options) @messageIo.sendMessage(TYPE.SQL_BATCH, payload.data) getInitialSql: -> xact_abort = if @config.options.abortTransactionOnError then 'on' else 'off' enableAnsiNullDefault = if @config.options.enableAnsiNullDefault then 'on' else 'off' """set textsize #{@config.options.textsize} set quoted_identifier on set arithabort off set numeric_roundabort off set ansi_warnings on set ansi_padding on set ansi_nulls on set ansi_null_dflt_on #{enableAnsiNullDefault} set concat_null_yields_null on set cursor_close_on_commit off set implicit_transactions off set language us_english set dateformat mdy set datefirst 7 set transaction isolation level #{@getIsolationLevelText @config.options.connectionIsolationLevel} set xact_abort #{xact_abort}""" processedInitialSql: -> @clearConnectTimer() @emit('connect') processLogin7Response: -> if @loggedIn @dispatchEvent('loggedIn') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') processLogin7NTLMResponse: -> if @ntlmpacket @dispatchEvent('receivedChallenge') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') processLogin7NTLMAck: -> if @loggedIn @dispatchEvent('loggedIn') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') execSqlBatch: (request) -> @makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, @currentTransactionDescriptor(), @config.options)) execSql: (request) -> request.transformIntoExecuteSqlRpc() if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) newBulkLoad: (table, callback) -> return new BulkLoad(table, @config.options, callback) execBulkLoad: (bulkLoad) -> request = new Request(bulkLoad.getBulkInsertSql(), (error) => if error if error.code == 'UNKNOWN' error.message += ' This is likely because the schema of the BulkLoad does not match the schema of the table you are attempting to insert into.' bulkLoad.error = error bulkLoad.callback(error) else @makeRequest(bulkLoad, TYPE.BULK_LOAD, bulkLoad.getPayload()) ) @execSqlBatch(request) prepare: (request) -> request.transformIntoPrepareRpc() @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) unprepare: (request) -> request.transformIntoUnprepareRpc() @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) execute: (request, parameters) -> request.transformIntoExecuteRpc(parameters) if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) callProcedure: (request) -> request.validateParameters() if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) beginTransaction: (callback, name, isolationLevel) -> isolationLevel ||= @config.options.isolationLevel transaction = new Transaction(name || '', isolationLevel) if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "SET TRANSACTION ISOLATION LEVEL #{transaction.isolationLevelToTSQL()};BEGIN TRAN #{transaction.name}", callback request = new Request(undefined, (err) => callback(err, @currentTransactionDescriptor()) ) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(@currentTransactionDescriptor())) commitTransaction: (callback, name) -> transaction = new Transaction(name || '') if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "COMMIT TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(@currentTransactionDescriptor())) rollbackTransaction: (callback, name) -> transaction = new Transaction(name || '') if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "ROLLBACK TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(@currentTransactionDescriptor())) saveTransaction: (callback, name) -> transaction = new Transaction(name) if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "SAVE TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.savePayload(@currentTransactionDescriptor())) transaction: (cb, isolationLevel) -> if typeof cb != 'function' throw new TypeError('`cb` must be a function') useSavepoint = @inTransaction name = "_tedious_#{crypto.randomBytes(10).toString('hex')}" txDone = (err, done) => args = [] args.push(arguments[i]) for i in [2..arguments.length] if err if @inTransaction @rollbackTransaction((txErr) -> args.unshift(txErr || err) done.apply(null, args) , name) else # We're no longer inside a transaction. This happens if the outermost transaction # was rolled back, for one of the following reasons: # * Connection#rollbackTransaction was called. # * `ROLLBACK TRANSACTION` was executed. # * the server rolled back the transaction, due to a batch aborting error. # # As the transaction was already rolled back, we only need to propagate # the error through all callbacks. process.nextTick -> args.unshift(err) done.apply(null, args) else if useSavepoint process.nextTick -> args.unshift(null) done.apply(null, args) else @commitTransaction((txErr) -> args.unshift(txErr) done.apply(null, args) , name) if useSavepoint @saveTransaction((err) => return cb(err) if err if isolationLevel @execSqlBatch new Request "SET transaction isolation level #{@getIsolationLevelText(isolationLevel)}", (err) -> cb(err, txDone) else cb(null, txDone) , name) else @beginTransaction((err) -> return cb(err) if err cb(null, txDone) , name, isolationLevel) makeRequest: (request, packetType, payload) -> if @state != @STATE.LOGGED_IN message = "Requests can only be made in the #{@STATE.LOGGED_IN.name} state, not the #{@state.name} state" @debug.log(message) request.callback RequestError message, 'EINVALIDSTATE' else @request = request @request.rowCount = 0 @request.rows = [] @request.rst = [] @createRequestTimer() @messageIo.sendMessage(packetType, payload.data, @resetConnectionOnNextRequest) @resetConnectionOnNextRequest = false @debug.payload(-> payload.toString(' ') ) @transitionTo(@STATE.SENT_CLIENT_REQUEST) cancel: -> if @state != @STATE.SENT_CLIENT_REQUEST message = "Requests can only be canceled in the #{@STATE.SENT_CLIENT_REQUEST.name} state, not the #{@state.name} state" @debug.log(message) false else @request.canceled = true @messageIo.sendMessage(TYPE.ATTENTION) @transitionTo(@STATE.SENT_ATTENTION) true reset: (callback) => request = new Request(@getInitialSql(), (err, rowCount, rows) -> callback(err) ) @resetConnectionOnNextRequest = true @execSqlBatch(request) currentTransactionDescriptor: -> @transactionDescriptors[@transactionDescriptors.length - 1] getIsolationLevelText: (isolationLevel) -> switch isolationLevel when ISOLATION_LEVEL.READ_UNCOMMITTED then 'read uncommitted' when ISOLATION_LEVEL.REPEATABLE_READ then 'repeatable read' when ISOLATION_LEVEL.SERIALIZABLE then 'serializable' when ISOLATION_LEVEL.SNAPSHOT then 'snapshot' else 'read committed' module.exports = Connection
14970
require('./buffertools') BulkLoad = require('./bulk-load') Debug = require('./debug') EventEmitter = require('events').EventEmitter instanceLookup = require('./instance-lookup').instanceLookup TYPE = require('./packet').TYPE PreloginPayload = require('./prelogin-payload') Login7Payload = require('./login7-payload') NTLMResponsePayload = require('./ntlm-payload') Request = require('./request') RpcRequestPayload = require('./rpcrequest-payload') SqlBatchPayload = require('./sqlbatch-payload') MessageIO = require('./message-io') Socket = require('net').Socket TokenStreamParser = require('./token/token-stream-parser').Parser Transaction = require('./transaction').Transaction ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL crypto = require('crypto') tls = require('tls') {ConnectionError, RequestError} = require('./errors') # A rather basic state machine for managing a connection. # Implements something approximating s3.2.1. KEEP_ALIVE_INITIAL_DELAY = 30 * 1000 DEFAULT_CONNECT_TIMEOUT = 15 * 1000 DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000 DEFAULT_CANCEL_TIMEOUT = 5 * 1000 DEFAULT_PACKET_SIZE = 4 * 1024 DEFAULT_TEXTSIZE = '2147483647' DEFAULT_PORT = 1433 DEFAULT_TDS_VERSION = '7_4' class Connection extends EventEmitter STATE: CONNECTING: name: 'Connecting' enter: -> @initialiseConnection() events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) socketConnect: -> @sendPreLogin() @transitionTo(@STATE.SENT_PRELOGIN) SENT_PRELOGIN: name: 'SentPrelogin' enter: -> @emptyMessageBuffer() events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @addToMessageBuffer(data) message: -> @processPreLoginResponse() noTls: -> @sendLogin7Packet() if @config.domain @transitionTo(@STATE.SENT_LOGIN7_WITH_NTLM) else @transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN) tls: -> @initiateTlsSslHandshake() @sendLogin7Packet() @transitionTo(@STATE.SENT_TLSSSLNEGOTIATION) REROUTING: name: 'ReRouting' enter: -> @cleanupConnection(true) events: message: -> socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) reconnect: -> @config.server = @routingData.server @config.options.port = @routingData.port @transitionTo(@STATE.CONNECTING) SENT_TLSSSLNEGOTIATION: name: 'SentTLSSSLNegotiation' enter: -> @tlsNegotiationComplete = false events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @securePair.encrypted.write(data) tlsNegotiated: -> @tlsNegotiationComplete = true message: -> if @tlsNegotiationComplete @transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN) else SENT_LOGIN7_WITH_STANDARD_LOGIN: name: 'SentLogin7WithStandardLogin' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) loggedIn: -> @transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL) routingChange: -> @transitionTo(@STATE.REROUTING) loginFailed: -> @transitionTo(@STATE.FINAL) message: -> @processLogin7Response() SENT_LOGIN7_WITH_NTLM: name: 'SentLogin7WithNTLMLogin' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) receivedChallenge: -> @sendNTLMResponsePacket() @transitionTo(@STATE.SENT_NTLM_RESPONSE) loginFailed: -> @transitionTo(@STATE.FINAL) message: -> @processLogin7NTLMResponse() SENT_NTLM_RESPONSE: name: 'SentNTLMResponse' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) loggedIn: -> @transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL) loginFailed: -> @transitionTo(@STATE.FINAL) routingChange: -> @transitionTo(@STATE.REROUTING) message: -> @processLogin7NTLMAck() LOGGED_IN_SENDING_INITIAL_SQL: name: 'LoggedInSendingInitialSql' enter: -> @sendInitialSql() events: connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) message: (error) -> @transitionTo(@STATE.LOGGED_IN) @processedInitialSql() LOGGED_IN: name: 'LoggedIn' events: socketError: (error) -> @transitionTo(@STATE.FINAL) SENT_CLIENT_REQUEST: name: 'SentClientRequest' events: socketError: (error) -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) message: -> @clearRequestTimer() @transitionTo(@STATE.LOGGED_IN) sqlRequest = @request @request = undefined sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows) SENT_ATTENTION: name: 'SentAttention' enter: -> @attentionReceived = false events: socketError: (error) -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) attention: -> @attentionReceived = true message: -> # 3.2.5.7 Sent Attention State # Discard any data contained in the response, until we receive the attention response if @attentionReceived sqlRequest = @request @request = undefined @transitionTo(@STATE.LOGGED_IN) if sqlRequest.canceled sqlRequest.callback(RequestError("Canceled.", 'ECANCEL')) else message = "Timeout: Request failed to complete in #{@config.options.requestTimeout}ms" sqlRequest.callback(RequestError(message, 'ETIMEOUT')) FINAL: name: 'Final' enter: -> @cleanupConnection() events: loginFailed: -> # Do nothing. The connection was probably closed by the client code. connectTimeout: -> # Do nothing, as the timer should be cleaned up. message: -> # Do nothing socketError: -> # Do nothing constructor: (@config) -> @defaultConfig() @createDebug() @createTokenStreamParser() @inTransaction = false @transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])] @transitionTo(@STATE.CONNECTING) close: -> @transitionTo(@STATE.FINAL) initialiseConnection: -> @connect() @createConnectTimer() cleanupConnection: (@redirect)-> if !@closed @clearConnectTimer() @clearRequestTimer() @closeConnection() if !@redirect @emit('end') else @emit('rerouting') @closed = true @loggedIn = false @loginError = null defaultConfig: -> @config.options ||= {} @config.options.textsize ||= DEFAULT_TEXTSIZE @config.options.connectTimeout ||= DEFAULT_CONNECT_TIMEOUT @config.options.requestTimeout ?= DEFAULT_CLIENT_REQUEST_TIMEOUT @config.options.cancelTimeout ?= DEFAULT_CANCEL_TIMEOUT @config.options.packetSize ||= DEFAULT_PACKET_SIZE @config.options.tdsVersion ||= DEFAULT_TDS_VERSION @config.options.isolationLevel ||= ISOLATION_LEVEL.READ_COMMITTED @config.options.encrypt ||= false @config.options.cryptoCredentialsDetails ||= {} @config.options.useUTC ?= true @config.options.useColumnNames ?= false @config.options.connectionIsolationLevel ||= ISOLATION_LEVEL.READ_COMMITTED @config.options.readOnlyIntent ?= false @config.options.enableAnsiNullDefault ?= true if !@config.options.port && !@config.options.instanceName @config.options.port = DEFAULT_PORT else if @config.options.port && @config.options.instanceName throw new Error("Port and instanceName are mutually exclusive, but #{@config.options.port} and #{@config.options.instanceName} provided") else if @config.options.port if @config.options.port < 0 or @config.options.port > 65536 throw new RangeError "Port should be > 0 and < 65536" if @config.options.columnNameReplacer && typeof @config.options.columnNameReplacer != 'function' throw new TypeError('options.columnNameReplacer must be a function or null.') createDebug: -> @debug = new Debug(@config.options.debug) @debug.on('debug', (message) => @emit('debug', message) ) createTokenStreamParser: -> @tokenStreamParser = new TokenStreamParser(@debug, undefined, @config.options) @tokenStreamParser.on('infoMessage', (token) => @emit('infoMessage', token) ) @tokenStreamParser.on('sspichallenge', (token) => if token.ntlmpacket @ntlmpacket = token.ntlmpacket @emit('sspichallenge', token) ) @tokenStreamParser.on('errorMessage', (token) => @emit('errorMessage', token) if @loggedIn if @request @request.error = RequestError token.message, 'EREQUEST' @request.error.number = token.number @request.error.state = token.state @request.error.class = token.class @request.error.serverName = token.serverName @request.error.procName = token.procName @request.error.lineNumber = token.lineNumber else @loginError = ConnectionError token.message, 'ELOGIN' ) @tokenStreamParser.on('databaseChange', (token) => @emit('databaseChange', token.newValue) ) @tokenStreamParser.on('languageChange', (token) => @emit('languageChange', token.newValue) ) @tokenStreamParser.on('charsetChange', (token) => @emit('charsetChange', token.newValue) ) @tokenStreamParser.on('loginack', (token) => unless token.tdsVersion # unsupported TDS version @loginError = ConnectionError "Server responded with unknown TDS version.", 'ETDS' @loggedIn = false return unless token.interface # unsupported interface @loginError = ConnectionError "Server responded with unsupported interface.", 'EINTERFACENOTSUPP' @loggedIn = false return # use negotiated version @config.options.tdsVersion = token.tdsVersion @loggedIn = true ) @tokenStreamParser.on('routingChange', (token) => @routingData = token.newValue @dispatchEvent('routingChange') ) @tokenStreamParser.on('packetSizeChange', (token) => @messageIo.packetSize(token.newValue) ) # A new top-level transaction was started. This is not fired # for nested transactions. @tokenStreamParser.on('beginTransaction', (token) => @transactionDescriptors.push(token.newValue) @inTransaction = true ) # A top-level transaction was committed. This is not fired # for nested transactions. @tokenStreamParser.on('commitTransaction', (token) => @transactionDescriptors.length = 1 @inTransaction = false ) # A top-level transaction was rolled back. This is not fired # for nested transactions. This is also fired if a batch # aborting error happened that caused a rollback. @tokenStreamParser.on('rollbackTransaction', (token) => @transactionDescriptors.length = 1 # An outermost transaction was rolled back. Reset the transaction counter @inTransaction = false @emit('rollbackTransaction') ) @tokenStreamParser.on('columnMetadata', (token) => if @request if @config.options.useColumnNames columns = {} columns[col.colName] = col for col in token.columns when not columns[col.colName]? else columns = token.columns @request.emit('columnMetadata', columns) else @emit 'error', new Error "Received 'columnMetadata' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('order', (token) => if @request @request.emit('order', token.orderColumns) else @emit 'error', new Error "Received 'order' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('row', (token) => if @request if @config.options.rowCollectionOnRequestCompletion @request.rows.push token.columns if @config.options.rowCollectionOnDone @request.rst.push token.columns @request.emit('row', token.columns) else @emit 'error', new Error "Received 'row' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('returnStatus', (token) => if @request # Keep value for passing in 'doneProc' event. @procReturnStatusValue = token.value ) @tokenStreamParser.on('returnValue', (token) => if @request @request.emit('returnValue', token.paramName, token.value, token.metadata) ) @tokenStreamParser.on('doneProc', (token) => if @request @request.emit('doneProc', token.rowCount, token.more, @procReturnStatusValue, @request.rst) @procReturnStatusValue = undefined if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('doneInProc', (token) => if @request @request.emit('doneInProc', token.rowCount, token.more, @request.rst) if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('done', (token) => if @request if token.attention @dispatchEvent("attention") # check if the DONE_ERROR flags was set, but an ERROR token was not sent. if token.sqlError && !@request.error @request.error = RequestError('An unknown error has occurred.', 'UNKNOWN') @request.emit('done', token.rowCount, token.more, @request.rst) if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('resetConnection', (token) => @emit('resetConnection') ) @tokenStreamParser.on('tokenStreamError', (error) => @emit 'error', error @close() ) connect: -> if (@config.options.port) @connectOnPort(@config.options.port) else instanceLookup( @config.server @config.options.instanceName (message, port) => if @state == @STATE.FINAL return if message @emit('connect', ConnectionError(message, 'EINSTLOOKUP')) else @connectOnPort(port) @config.options.connectTimeout) connectOnPort: (port) -> @socket = new Socket({}) connectOpts = host: @config.server port: port if @config.options.localAddress connectOpts.localAddress = @config.options.localAddress @socket.connect(connectOpts) @socket.on('error', @socketError) @socket.on('connect', @socketConnect) @socket.on('close', @socketClose) @socket.on('end', @socketEnd) @messageIo = new MessageIO(@socket, @config.options.packetSize, @debug) @messageIo.on('data', (data) => @dispatchEvent('data', data) ) @messageIo.on('message', => @dispatchEvent('message') ) closeConnection: -> @socket?.destroy() createConnectTimer: -> @connectTimer = setTimeout(@connectTimeout, @config.options.connectTimeout) createRequestTimer: -> if @config.options.requestTimeout @requestTimer = setTimeout(@requestTimeout, @config.options.requestTimeout) connectTimeout: => message = "Failed to connect to #{@config.server}:#{@config.options.port} in #{@config.options.connectTimeout}ms" @debug.log(message) @emit('connect', ConnectionError(message, 'ETIMEOUT')) @connectTimer = undefined @dispatchEvent('connectTimeout') requestTimeout: => @requestTimer = undefined @messageIo.sendMessage(TYPE.ATTENTION) @transitionTo(@STATE.SENT_ATTENTION) clearConnectTimer: -> if @connectTimer clearTimeout(@connectTimer) clearRequestTimer: -> if @requestTimer clearTimeout(@requestTimer) transitionTo: (newState) -> if @state == newState @debug.log("State is already #{newState.name}") return if @state?.exit @state.exit.apply(@) @debug.log("State change: #{@state?.name} -> #{newState.name}") @state = newState if @state.enter @state.enter.apply(@) dispatchEvent: (eventName, args...) -> if @state?.events[eventName] eventFunction = @state.events[eventName].apply(@, args) else @emit 'error', new Error "No event '#{eventName}' in state '#{@state.name}'" @close() socketError: (error) => if @state == @STATE.CONNECTING message = "Failed to connect to #{@config.server}:#{@config.options.port} - #{error.message}" @debug.log(message) @emit('connect', ConnectionError(message, 'ESOCKET')) else message = "Connection lost - #{error.message}" @debug.log(message) @emit('error', ConnectionError(message, 'ESOCKET')) @dispatchEvent('socketError', error) socketConnect: => @socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY) @closed = false @debug.log("connected to #{@config.server}:#{@config.options.port}") @dispatchEvent('socketConnect') socketEnd: => @debug.log("socket ended") @transitionTo(@STATE.FINAL) socketClose: => @debug.log("connection to #{@config.server}:#{@config.options.port} closed") if @state is @STATE.REROUTING @debug.log("Rerouting to #{@routingData.server}:#{@routingData.port}") @dispatchEvent('reconnect') else @transitionTo(@STATE.FINAL) sendPreLogin: -> payload = new PreloginPayload({encrypt: @config.options.encrypt}) @messageIo.sendMessage(TYPE.PRELOGIN, payload.data) @debug.payload(-> payload.toString(' ') ) emptyMessageBuffer: -> @messageBuffer = new Buffer(0) addToMessageBuffer: (data) -> @messageBuffer = Buffer.concat([@messageBuffer, data]) processPreLoginResponse: -> preloginPayload = new PreloginPayload(@messageBuffer) @debug.payload(-> preloginPayload.toString(' ') ) if preloginPayload.encryptionString in ['ON','REQ'] @dispatchEvent('tls') else @dispatchEvent('noTls') sendLogin7Packet: -> loginData = domain: @config.domain userName: @config.userName password: <PASSWORD> database: @config.options.database serverName: @config.server appName: @config.options.appName packetSize: @config.options.packetSize tdsVersion: @config.options.tdsVersion initDbFatal: not @config.options.fallbackToDefaultDb readOnlyIntent: @config.options.readOnlyIntent payload = new Login7Payload(loginData) @messageIo.sendMessage(TYPE.LOGIN7, payload.data) @debug.payload(-> payload.toString(' ') ) sendNTLMResponsePacket: -> responseData = domain: @config.domain userName: @config.userName password: <PASSWORD> database: @config.options.database appName: @config.options.appName packetSize: @config.options.packetSize tdsVersion: @config.options.tdsVersion ntlmpacket: @ntlmpacket additional: @additional payload = new NTLMResponsePayload(responseData) @messageIo.sendMessage(TYPE.NTLMAUTH_PKT, payload.data) @debug.payload -> payload.toString ' ' initiateTlsSslHandshake: -> credentials = if tls.createSecureContext tls.createSecureContext(@config.options.cryptoCredentialsDetails) else crypto.createCredentials(@config.options.cryptoCredentialsDetails) @securePair = tls.createSecurePair(credentials) @securePair.on('secure', => cipher = @securePair.cleartext.getCipher() @debug.log("TLS negotiated (#{cipher.name}, #{cipher.version})") # console.log cipher # console.log @securePair.cleartext.getPeerCertificate() @emit('secure', @securePair.cleartext) @messageIo.encryptAllFutureTraffic() @dispatchEvent('tlsNegotiated') ) @securePair.encrypted.on('data', (data) => @messageIo.sendMessage(TYPE.PRELOGIN, data) ) @messageIo.tlsNegotiationStarting(@securePair) sendDataToTokenStreamParser: (data) -> @tokenStreamParser.addBuffer(data) sendInitialSql: -> payload = new SqlBatchPayload(@getInitialSql(), @currentTransactionDescriptor(), @config.options) @messageIo.sendMessage(TYPE.SQL_BATCH, payload.data) getInitialSql: -> xact_abort = if @config.options.abortTransactionOnError then 'on' else 'off' enableAnsiNullDefault = if @config.options.enableAnsiNullDefault then 'on' else 'off' """set textsize #{@config.options.textsize} set quoted_identifier on set arithabort off set numeric_roundabort off set ansi_warnings on set ansi_padding on set ansi_nulls on set ansi_null_dflt_on #{enableAnsiNullDefault} set concat_null_yields_null on set cursor_close_on_commit off set implicit_transactions off set language us_english set dateformat mdy set datefirst 7 set transaction isolation level #{@getIsolationLevelText @config.options.connectionIsolationLevel} set xact_abort #{xact_abort}""" processedInitialSql: -> @clearConnectTimer() @emit('connect') processLogin7Response: -> if @loggedIn @dispatchEvent('loggedIn') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') processLogin7NTLMResponse: -> if @ntlmpacket @dispatchEvent('receivedChallenge') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') processLogin7NTLMAck: -> if @loggedIn @dispatchEvent('loggedIn') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') execSqlBatch: (request) -> @makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, @currentTransactionDescriptor(), @config.options)) execSql: (request) -> request.transformIntoExecuteSqlRpc() if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) newBulkLoad: (table, callback) -> return new BulkLoad(table, @config.options, callback) execBulkLoad: (bulkLoad) -> request = new Request(bulkLoad.getBulkInsertSql(), (error) => if error if error.code == 'UNKNOWN' error.message += ' This is likely because the schema of the BulkLoad does not match the schema of the table you are attempting to insert into.' bulkLoad.error = error bulkLoad.callback(error) else @makeRequest(bulkLoad, TYPE.BULK_LOAD, bulkLoad.getPayload()) ) @execSqlBatch(request) prepare: (request) -> request.transformIntoPrepareRpc() @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) unprepare: (request) -> request.transformIntoUnprepareRpc() @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) execute: (request, parameters) -> request.transformIntoExecuteRpc(parameters) if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) callProcedure: (request) -> request.validateParameters() if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) beginTransaction: (callback, name, isolationLevel) -> isolationLevel ||= @config.options.isolationLevel transaction = new Transaction(name || '', isolationLevel) if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "SET TRANSACTION ISOLATION LEVEL #{transaction.isolationLevelToTSQL()};BEGIN TRAN #{transaction.name}", callback request = new Request(undefined, (err) => callback(err, @currentTransactionDescriptor()) ) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(@currentTransactionDescriptor())) commitTransaction: (callback, name) -> transaction = new Transaction(name || '') if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "COMMIT TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(@currentTransactionDescriptor())) rollbackTransaction: (callback, name) -> transaction = new Transaction(name || '') if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "ROLLBACK TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(@currentTransactionDescriptor())) saveTransaction: (callback, name) -> transaction = new Transaction(name) if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "SAVE TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.savePayload(@currentTransactionDescriptor())) transaction: (cb, isolationLevel) -> if typeof cb != 'function' throw new TypeError('`cb` must be a function') useSavepoint = @inTransaction name = "_tedious_#{crypto.randomBytes(10).toString('hex')}" txDone = (err, done) => args = [] args.push(arguments[i]) for i in [2..arguments.length] if err if @inTransaction @rollbackTransaction((txErr) -> args.unshift(txErr || err) done.apply(null, args) , name) else # We're no longer inside a transaction. This happens if the outermost transaction # was rolled back, for one of the following reasons: # * Connection#rollbackTransaction was called. # * `ROLLBACK TRANSACTION` was executed. # * the server rolled back the transaction, due to a batch aborting error. # # As the transaction was already rolled back, we only need to propagate # the error through all callbacks. process.nextTick -> args.unshift(err) done.apply(null, args) else if useSavepoint process.nextTick -> args.unshift(null) done.apply(null, args) else @commitTransaction((txErr) -> args.unshift(txErr) done.apply(null, args) , name) if useSavepoint @saveTransaction((err) => return cb(err) if err if isolationLevel @execSqlBatch new Request "SET transaction isolation level #{@getIsolationLevelText(isolationLevel)}", (err) -> cb(err, txDone) else cb(null, txDone) , name) else @beginTransaction((err) -> return cb(err) if err cb(null, txDone) , name, isolationLevel) makeRequest: (request, packetType, payload) -> if @state != @STATE.LOGGED_IN message = "Requests can only be made in the #{@STATE.LOGGED_IN.name} state, not the #{@state.name} state" @debug.log(message) request.callback RequestError message, 'EINVALIDSTATE' else @request = request @request.rowCount = 0 @request.rows = [] @request.rst = [] @createRequestTimer() @messageIo.sendMessage(packetType, payload.data, @resetConnectionOnNextRequest) @resetConnectionOnNextRequest = false @debug.payload(-> payload.toString(' ') ) @transitionTo(@STATE.SENT_CLIENT_REQUEST) cancel: -> if @state != @STATE.SENT_CLIENT_REQUEST message = "Requests can only be canceled in the #{@STATE.SENT_CLIENT_REQUEST.name} state, not the #{@state.name} state" @debug.log(message) false else @request.canceled = true @messageIo.sendMessage(TYPE.ATTENTION) @transitionTo(@STATE.SENT_ATTENTION) true reset: (callback) => request = new Request(@getInitialSql(), (err, rowCount, rows) -> callback(err) ) @resetConnectionOnNextRequest = true @execSqlBatch(request) currentTransactionDescriptor: -> @transactionDescriptors[@transactionDescriptors.length - 1] getIsolationLevelText: (isolationLevel) -> switch isolationLevel when ISOLATION_LEVEL.READ_UNCOMMITTED then 'read uncommitted' when ISOLATION_LEVEL.REPEATABLE_READ then 'repeatable read' when ISOLATION_LEVEL.SERIALIZABLE then 'serializable' when ISOLATION_LEVEL.SNAPSHOT then 'snapshot' else 'read committed' module.exports = Connection
true
require('./buffertools') BulkLoad = require('./bulk-load') Debug = require('./debug') EventEmitter = require('events').EventEmitter instanceLookup = require('./instance-lookup').instanceLookup TYPE = require('./packet').TYPE PreloginPayload = require('./prelogin-payload') Login7Payload = require('./login7-payload') NTLMResponsePayload = require('./ntlm-payload') Request = require('./request') RpcRequestPayload = require('./rpcrequest-payload') SqlBatchPayload = require('./sqlbatch-payload') MessageIO = require('./message-io') Socket = require('net').Socket TokenStreamParser = require('./token/token-stream-parser').Parser Transaction = require('./transaction').Transaction ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL crypto = require('crypto') tls = require('tls') {ConnectionError, RequestError} = require('./errors') # A rather basic state machine for managing a connection. # Implements something approximating s3.2.1. KEEP_ALIVE_INITIAL_DELAY = 30 * 1000 DEFAULT_CONNECT_TIMEOUT = 15 * 1000 DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000 DEFAULT_CANCEL_TIMEOUT = 5 * 1000 DEFAULT_PACKET_SIZE = 4 * 1024 DEFAULT_TEXTSIZE = '2147483647' DEFAULT_PORT = 1433 DEFAULT_TDS_VERSION = '7_4' class Connection extends EventEmitter STATE: CONNECTING: name: 'Connecting' enter: -> @initialiseConnection() events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) socketConnect: -> @sendPreLogin() @transitionTo(@STATE.SENT_PRELOGIN) SENT_PRELOGIN: name: 'SentPrelogin' enter: -> @emptyMessageBuffer() events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @addToMessageBuffer(data) message: -> @processPreLoginResponse() noTls: -> @sendLogin7Packet() if @config.domain @transitionTo(@STATE.SENT_LOGIN7_WITH_NTLM) else @transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN) tls: -> @initiateTlsSslHandshake() @sendLogin7Packet() @transitionTo(@STATE.SENT_TLSSSLNEGOTIATION) REROUTING: name: 'ReRouting' enter: -> @cleanupConnection(true) events: message: -> socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) reconnect: -> @config.server = @routingData.server @config.options.port = @routingData.port @transitionTo(@STATE.CONNECTING) SENT_TLSSSLNEGOTIATION: name: 'SentTLSSSLNegotiation' enter: -> @tlsNegotiationComplete = false events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @securePair.encrypted.write(data) tlsNegotiated: -> @tlsNegotiationComplete = true message: -> if @tlsNegotiationComplete @transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN) else SENT_LOGIN7_WITH_STANDARD_LOGIN: name: 'SentLogin7WithStandardLogin' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) loggedIn: -> @transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL) routingChange: -> @transitionTo(@STATE.REROUTING) loginFailed: -> @transitionTo(@STATE.FINAL) message: -> @processLogin7Response() SENT_LOGIN7_WITH_NTLM: name: 'SentLogin7WithNTLMLogin' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) receivedChallenge: -> @sendNTLMResponsePacket() @transitionTo(@STATE.SENT_NTLM_RESPONSE) loginFailed: -> @transitionTo(@STATE.FINAL) message: -> @processLogin7NTLMResponse() SENT_NTLM_RESPONSE: name: 'SentNTLMResponse' events: socketError: (error) -> @transitionTo(@STATE.FINAL) connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) loggedIn: -> @transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL) loginFailed: -> @transitionTo(@STATE.FINAL) routingChange: -> @transitionTo(@STATE.REROUTING) message: -> @processLogin7NTLMAck() LOGGED_IN_SENDING_INITIAL_SQL: name: 'LoggedInSendingInitialSql' enter: -> @sendInitialSql() events: connectTimeout: -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) message: (error) -> @transitionTo(@STATE.LOGGED_IN) @processedInitialSql() LOGGED_IN: name: 'LoggedIn' events: socketError: (error) -> @transitionTo(@STATE.FINAL) SENT_CLIENT_REQUEST: name: 'SentClientRequest' events: socketError: (error) -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) message: -> @clearRequestTimer() @transitionTo(@STATE.LOGGED_IN) sqlRequest = @request @request = undefined sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows) SENT_ATTENTION: name: 'SentAttention' enter: -> @attentionReceived = false events: socketError: (error) -> @transitionTo(@STATE.FINAL) data: (data) -> @sendDataToTokenStreamParser(data) attention: -> @attentionReceived = true message: -> # 3.2.5.7 Sent Attention State # Discard any data contained in the response, until we receive the attention response if @attentionReceived sqlRequest = @request @request = undefined @transitionTo(@STATE.LOGGED_IN) if sqlRequest.canceled sqlRequest.callback(RequestError("Canceled.", 'ECANCEL')) else message = "Timeout: Request failed to complete in #{@config.options.requestTimeout}ms" sqlRequest.callback(RequestError(message, 'ETIMEOUT')) FINAL: name: 'Final' enter: -> @cleanupConnection() events: loginFailed: -> # Do nothing. The connection was probably closed by the client code. connectTimeout: -> # Do nothing, as the timer should be cleaned up. message: -> # Do nothing socketError: -> # Do nothing constructor: (@config) -> @defaultConfig() @createDebug() @createTokenStreamParser() @inTransaction = false @transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])] @transitionTo(@STATE.CONNECTING) close: -> @transitionTo(@STATE.FINAL) initialiseConnection: -> @connect() @createConnectTimer() cleanupConnection: (@redirect)-> if !@closed @clearConnectTimer() @clearRequestTimer() @closeConnection() if !@redirect @emit('end') else @emit('rerouting') @closed = true @loggedIn = false @loginError = null defaultConfig: -> @config.options ||= {} @config.options.textsize ||= DEFAULT_TEXTSIZE @config.options.connectTimeout ||= DEFAULT_CONNECT_TIMEOUT @config.options.requestTimeout ?= DEFAULT_CLIENT_REQUEST_TIMEOUT @config.options.cancelTimeout ?= DEFAULT_CANCEL_TIMEOUT @config.options.packetSize ||= DEFAULT_PACKET_SIZE @config.options.tdsVersion ||= DEFAULT_TDS_VERSION @config.options.isolationLevel ||= ISOLATION_LEVEL.READ_COMMITTED @config.options.encrypt ||= false @config.options.cryptoCredentialsDetails ||= {} @config.options.useUTC ?= true @config.options.useColumnNames ?= false @config.options.connectionIsolationLevel ||= ISOLATION_LEVEL.READ_COMMITTED @config.options.readOnlyIntent ?= false @config.options.enableAnsiNullDefault ?= true if !@config.options.port && !@config.options.instanceName @config.options.port = DEFAULT_PORT else if @config.options.port && @config.options.instanceName throw new Error("Port and instanceName are mutually exclusive, but #{@config.options.port} and #{@config.options.instanceName} provided") else if @config.options.port if @config.options.port < 0 or @config.options.port > 65536 throw new RangeError "Port should be > 0 and < 65536" if @config.options.columnNameReplacer && typeof @config.options.columnNameReplacer != 'function' throw new TypeError('options.columnNameReplacer must be a function or null.') createDebug: -> @debug = new Debug(@config.options.debug) @debug.on('debug', (message) => @emit('debug', message) ) createTokenStreamParser: -> @tokenStreamParser = new TokenStreamParser(@debug, undefined, @config.options) @tokenStreamParser.on('infoMessage', (token) => @emit('infoMessage', token) ) @tokenStreamParser.on('sspichallenge', (token) => if token.ntlmpacket @ntlmpacket = token.ntlmpacket @emit('sspichallenge', token) ) @tokenStreamParser.on('errorMessage', (token) => @emit('errorMessage', token) if @loggedIn if @request @request.error = RequestError token.message, 'EREQUEST' @request.error.number = token.number @request.error.state = token.state @request.error.class = token.class @request.error.serverName = token.serverName @request.error.procName = token.procName @request.error.lineNumber = token.lineNumber else @loginError = ConnectionError token.message, 'ELOGIN' ) @tokenStreamParser.on('databaseChange', (token) => @emit('databaseChange', token.newValue) ) @tokenStreamParser.on('languageChange', (token) => @emit('languageChange', token.newValue) ) @tokenStreamParser.on('charsetChange', (token) => @emit('charsetChange', token.newValue) ) @tokenStreamParser.on('loginack', (token) => unless token.tdsVersion # unsupported TDS version @loginError = ConnectionError "Server responded with unknown TDS version.", 'ETDS' @loggedIn = false return unless token.interface # unsupported interface @loginError = ConnectionError "Server responded with unsupported interface.", 'EINTERFACENOTSUPP' @loggedIn = false return # use negotiated version @config.options.tdsVersion = token.tdsVersion @loggedIn = true ) @tokenStreamParser.on('routingChange', (token) => @routingData = token.newValue @dispatchEvent('routingChange') ) @tokenStreamParser.on('packetSizeChange', (token) => @messageIo.packetSize(token.newValue) ) # A new top-level transaction was started. This is not fired # for nested transactions. @tokenStreamParser.on('beginTransaction', (token) => @transactionDescriptors.push(token.newValue) @inTransaction = true ) # A top-level transaction was committed. This is not fired # for nested transactions. @tokenStreamParser.on('commitTransaction', (token) => @transactionDescriptors.length = 1 @inTransaction = false ) # A top-level transaction was rolled back. This is not fired # for nested transactions. This is also fired if a batch # aborting error happened that caused a rollback. @tokenStreamParser.on('rollbackTransaction', (token) => @transactionDescriptors.length = 1 # An outermost transaction was rolled back. Reset the transaction counter @inTransaction = false @emit('rollbackTransaction') ) @tokenStreamParser.on('columnMetadata', (token) => if @request if @config.options.useColumnNames columns = {} columns[col.colName] = col for col in token.columns when not columns[col.colName]? else columns = token.columns @request.emit('columnMetadata', columns) else @emit 'error', new Error "Received 'columnMetadata' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('order', (token) => if @request @request.emit('order', token.orderColumns) else @emit 'error', new Error "Received 'order' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('row', (token) => if @request if @config.options.rowCollectionOnRequestCompletion @request.rows.push token.columns if @config.options.rowCollectionOnDone @request.rst.push token.columns @request.emit('row', token.columns) else @emit 'error', new Error "Received 'row' when no sqlRequest is in progress" @close() ) @tokenStreamParser.on('returnStatus', (token) => if @request # Keep value for passing in 'doneProc' event. @procReturnStatusValue = token.value ) @tokenStreamParser.on('returnValue', (token) => if @request @request.emit('returnValue', token.paramName, token.value, token.metadata) ) @tokenStreamParser.on('doneProc', (token) => if @request @request.emit('doneProc', token.rowCount, token.more, @procReturnStatusValue, @request.rst) @procReturnStatusValue = undefined if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('doneInProc', (token) => if @request @request.emit('doneInProc', token.rowCount, token.more, @request.rst) if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('done', (token) => if @request if token.attention @dispatchEvent("attention") # check if the DONE_ERROR flags was set, but an ERROR token was not sent. if token.sqlError && !@request.error @request.error = RequestError('An unknown error has occurred.', 'UNKNOWN') @request.emit('done', token.rowCount, token.more, @request.rst) if token.rowCount != undefined @request.rowCount += token.rowCount if @config.options.rowCollectionOnDone @request.rst = [] ) @tokenStreamParser.on('resetConnection', (token) => @emit('resetConnection') ) @tokenStreamParser.on('tokenStreamError', (error) => @emit 'error', error @close() ) connect: -> if (@config.options.port) @connectOnPort(@config.options.port) else instanceLookup( @config.server @config.options.instanceName (message, port) => if @state == @STATE.FINAL return if message @emit('connect', ConnectionError(message, 'EINSTLOOKUP')) else @connectOnPort(port) @config.options.connectTimeout) connectOnPort: (port) -> @socket = new Socket({}) connectOpts = host: @config.server port: port if @config.options.localAddress connectOpts.localAddress = @config.options.localAddress @socket.connect(connectOpts) @socket.on('error', @socketError) @socket.on('connect', @socketConnect) @socket.on('close', @socketClose) @socket.on('end', @socketEnd) @messageIo = new MessageIO(@socket, @config.options.packetSize, @debug) @messageIo.on('data', (data) => @dispatchEvent('data', data) ) @messageIo.on('message', => @dispatchEvent('message') ) closeConnection: -> @socket?.destroy() createConnectTimer: -> @connectTimer = setTimeout(@connectTimeout, @config.options.connectTimeout) createRequestTimer: -> if @config.options.requestTimeout @requestTimer = setTimeout(@requestTimeout, @config.options.requestTimeout) connectTimeout: => message = "Failed to connect to #{@config.server}:#{@config.options.port} in #{@config.options.connectTimeout}ms" @debug.log(message) @emit('connect', ConnectionError(message, 'ETIMEOUT')) @connectTimer = undefined @dispatchEvent('connectTimeout') requestTimeout: => @requestTimer = undefined @messageIo.sendMessage(TYPE.ATTENTION) @transitionTo(@STATE.SENT_ATTENTION) clearConnectTimer: -> if @connectTimer clearTimeout(@connectTimer) clearRequestTimer: -> if @requestTimer clearTimeout(@requestTimer) transitionTo: (newState) -> if @state == newState @debug.log("State is already #{newState.name}") return if @state?.exit @state.exit.apply(@) @debug.log("State change: #{@state?.name} -> #{newState.name}") @state = newState if @state.enter @state.enter.apply(@) dispatchEvent: (eventName, args...) -> if @state?.events[eventName] eventFunction = @state.events[eventName].apply(@, args) else @emit 'error', new Error "No event '#{eventName}' in state '#{@state.name}'" @close() socketError: (error) => if @state == @STATE.CONNECTING message = "Failed to connect to #{@config.server}:#{@config.options.port} - #{error.message}" @debug.log(message) @emit('connect', ConnectionError(message, 'ESOCKET')) else message = "Connection lost - #{error.message}" @debug.log(message) @emit('error', ConnectionError(message, 'ESOCKET')) @dispatchEvent('socketError', error) socketConnect: => @socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY) @closed = false @debug.log("connected to #{@config.server}:#{@config.options.port}") @dispatchEvent('socketConnect') socketEnd: => @debug.log("socket ended") @transitionTo(@STATE.FINAL) socketClose: => @debug.log("connection to #{@config.server}:#{@config.options.port} closed") if @state is @STATE.REROUTING @debug.log("Rerouting to #{@routingData.server}:#{@routingData.port}") @dispatchEvent('reconnect') else @transitionTo(@STATE.FINAL) sendPreLogin: -> payload = new PreloginPayload({encrypt: @config.options.encrypt}) @messageIo.sendMessage(TYPE.PRELOGIN, payload.data) @debug.payload(-> payload.toString(' ') ) emptyMessageBuffer: -> @messageBuffer = new Buffer(0) addToMessageBuffer: (data) -> @messageBuffer = Buffer.concat([@messageBuffer, data]) processPreLoginResponse: -> preloginPayload = new PreloginPayload(@messageBuffer) @debug.payload(-> preloginPayload.toString(' ') ) if preloginPayload.encryptionString in ['ON','REQ'] @dispatchEvent('tls') else @dispatchEvent('noTls') sendLogin7Packet: -> loginData = domain: @config.domain userName: @config.userName password: PI:PASSWORD:<PASSWORD>END_PI database: @config.options.database serverName: @config.server appName: @config.options.appName packetSize: @config.options.packetSize tdsVersion: @config.options.tdsVersion initDbFatal: not @config.options.fallbackToDefaultDb readOnlyIntent: @config.options.readOnlyIntent payload = new Login7Payload(loginData) @messageIo.sendMessage(TYPE.LOGIN7, payload.data) @debug.payload(-> payload.toString(' ') ) sendNTLMResponsePacket: -> responseData = domain: @config.domain userName: @config.userName password: PI:PASSWORD:<PASSWORD>END_PI database: @config.options.database appName: @config.options.appName packetSize: @config.options.packetSize tdsVersion: @config.options.tdsVersion ntlmpacket: @ntlmpacket additional: @additional payload = new NTLMResponsePayload(responseData) @messageIo.sendMessage(TYPE.NTLMAUTH_PKT, payload.data) @debug.payload -> payload.toString ' ' initiateTlsSslHandshake: -> credentials = if tls.createSecureContext tls.createSecureContext(@config.options.cryptoCredentialsDetails) else crypto.createCredentials(@config.options.cryptoCredentialsDetails) @securePair = tls.createSecurePair(credentials) @securePair.on('secure', => cipher = @securePair.cleartext.getCipher() @debug.log("TLS negotiated (#{cipher.name}, #{cipher.version})") # console.log cipher # console.log @securePair.cleartext.getPeerCertificate() @emit('secure', @securePair.cleartext) @messageIo.encryptAllFutureTraffic() @dispatchEvent('tlsNegotiated') ) @securePair.encrypted.on('data', (data) => @messageIo.sendMessage(TYPE.PRELOGIN, data) ) @messageIo.tlsNegotiationStarting(@securePair) sendDataToTokenStreamParser: (data) -> @tokenStreamParser.addBuffer(data) sendInitialSql: -> payload = new SqlBatchPayload(@getInitialSql(), @currentTransactionDescriptor(), @config.options) @messageIo.sendMessage(TYPE.SQL_BATCH, payload.data) getInitialSql: -> xact_abort = if @config.options.abortTransactionOnError then 'on' else 'off' enableAnsiNullDefault = if @config.options.enableAnsiNullDefault then 'on' else 'off' """set textsize #{@config.options.textsize} set quoted_identifier on set arithabort off set numeric_roundabort off set ansi_warnings on set ansi_padding on set ansi_nulls on set ansi_null_dflt_on #{enableAnsiNullDefault} set concat_null_yields_null on set cursor_close_on_commit off set implicit_transactions off set language us_english set dateformat mdy set datefirst 7 set transaction isolation level #{@getIsolationLevelText @config.options.connectionIsolationLevel} set xact_abort #{xact_abort}""" processedInitialSql: -> @clearConnectTimer() @emit('connect') processLogin7Response: -> if @loggedIn @dispatchEvent('loggedIn') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') processLogin7NTLMResponse: -> if @ntlmpacket @dispatchEvent('receivedChallenge') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') processLogin7NTLMAck: -> if @loggedIn @dispatchEvent('loggedIn') else if @loginError @emit('connect', @loginError) else @emit('connect', ConnectionError('Login failed.', 'ELOGIN')) @dispatchEvent('loginFailed') execSqlBatch: (request) -> @makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, @currentTransactionDescriptor(), @config.options)) execSql: (request) -> request.transformIntoExecuteSqlRpc() if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) newBulkLoad: (table, callback) -> return new BulkLoad(table, @config.options, callback) execBulkLoad: (bulkLoad) -> request = new Request(bulkLoad.getBulkInsertSql(), (error) => if error if error.code == 'UNKNOWN' error.message += ' This is likely because the schema of the BulkLoad does not match the schema of the table you are attempting to insert into.' bulkLoad.error = error bulkLoad.callback(error) else @makeRequest(bulkLoad, TYPE.BULK_LOAD, bulkLoad.getPayload()) ) @execSqlBatch(request) prepare: (request) -> request.transformIntoPrepareRpc() @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) unprepare: (request) -> request.transformIntoUnprepareRpc() @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) execute: (request, parameters) -> request.transformIntoExecuteRpc(parameters) if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) callProcedure: (request) -> request.validateParameters() if request.error? return process.nextTick => @debug.log request.error.message request.callback request.error @makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor(), @config.options)) beginTransaction: (callback, name, isolationLevel) -> isolationLevel ||= @config.options.isolationLevel transaction = new Transaction(name || '', isolationLevel) if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "SET TRANSACTION ISOLATION LEVEL #{transaction.isolationLevelToTSQL()};BEGIN TRAN #{transaction.name}", callback request = new Request(undefined, (err) => callback(err, @currentTransactionDescriptor()) ) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(@currentTransactionDescriptor())) commitTransaction: (callback, name) -> transaction = new Transaction(name || '') if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "COMMIT TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(@currentTransactionDescriptor())) rollbackTransaction: (callback, name) -> transaction = new Transaction(name || '') if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "ROLLBACK TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(@currentTransactionDescriptor())) saveTransaction: (callback, name) -> transaction = new Transaction(name) if @config.options.tdsVersion < "7_2" return @execSqlBatch new Request "SAVE TRAN #{transaction.name}", callback request = new Request(undefined, callback) @makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.savePayload(@currentTransactionDescriptor())) transaction: (cb, isolationLevel) -> if typeof cb != 'function' throw new TypeError('`cb` must be a function') useSavepoint = @inTransaction name = "_tedious_#{crypto.randomBytes(10).toString('hex')}" txDone = (err, done) => args = [] args.push(arguments[i]) for i in [2..arguments.length] if err if @inTransaction @rollbackTransaction((txErr) -> args.unshift(txErr || err) done.apply(null, args) , name) else # We're no longer inside a transaction. This happens if the outermost transaction # was rolled back, for one of the following reasons: # * Connection#rollbackTransaction was called. # * `ROLLBACK TRANSACTION` was executed. # * the server rolled back the transaction, due to a batch aborting error. # # As the transaction was already rolled back, we only need to propagate # the error through all callbacks. process.nextTick -> args.unshift(err) done.apply(null, args) else if useSavepoint process.nextTick -> args.unshift(null) done.apply(null, args) else @commitTransaction((txErr) -> args.unshift(txErr) done.apply(null, args) , name) if useSavepoint @saveTransaction((err) => return cb(err) if err if isolationLevel @execSqlBatch new Request "SET transaction isolation level #{@getIsolationLevelText(isolationLevel)}", (err) -> cb(err, txDone) else cb(null, txDone) , name) else @beginTransaction((err) -> return cb(err) if err cb(null, txDone) , name, isolationLevel) makeRequest: (request, packetType, payload) -> if @state != @STATE.LOGGED_IN message = "Requests can only be made in the #{@STATE.LOGGED_IN.name} state, not the #{@state.name} state" @debug.log(message) request.callback RequestError message, 'EINVALIDSTATE' else @request = request @request.rowCount = 0 @request.rows = [] @request.rst = [] @createRequestTimer() @messageIo.sendMessage(packetType, payload.data, @resetConnectionOnNextRequest) @resetConnectionOnNextRequest = false @debug.payload(-> payload.toString(' ') ) @transitionTo(@STATE.SENT_CLIENT_REQUEST) cancel: -> if @state != @STATE.SENT_CLIENT_REQUEST message = "Requests can only be canceled in the #{@STATE.SENT_CLIENT_REQUEST.name} state, not the #{@state.name} state" @debug.log(message) false else @request.canceled = true @messageIo.sendMessage(TYPE.ATTENTION) @transitionTo(@STATE.SENT_ATTENTION) true reset: (callback) => request = new Request(@getInitialSql(), (err, rowCount, rows) -> callback(err) ) @resetConnectionOnNextRequest = true @execSqlBatch(request) currentTransactionDescriptor: -> @transactionDescriptors[@transactionDescriptors.length - 1] getIsolationLevelText: (isolationLevel) -> switch isolationLevel when ISOLATION_LEVEL.READ_UNCOMMITTED then 'read uncommitted' when ISOLATION_LEVEL.REPEATABLE_READ then 'repeatable read' when ISOLATION_LEVEL.SERIALIZABLE then 'serializable' when ISOLATION_LEVEL.SNAPSHOT then 'snapshot' else 'read committed' module.exports = Connection
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999095797538757, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/account-edit.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @AccountEdit constructor: -> $(document).on 'input change', '.js-account-edit', @initializeUpdate $(document).on 'ajax:error', '.js-account-edit', @ajaxError $(document).on 'ajax:send', '.js-account-edit', @ajaxSaving $(document).on 'ajax:success', '.js-account-edit', @ajaxSaved initializeUpdate: (e) => form = e.currentTarget return if form.dataset.accountEditAutoSubmit != '1' @abortUpdate form @saving form form.debouncedUpdate ?= _.debounce @update, 1000 form.debouncedUpdate form ajaxError: (e) => @clearState e.currentTarget ajaxSaving: (e) => @saving e.currentTarget ajaxSaved: (e) => @saved e.currentTarget clearState: (el) => el.dataset.accountEditState = '' getValue: (form) -> if form.dataset.accountEditType == 'array' prevValue = null value = [''] for checkbox in form.querySelectorAll('input') value.push(checkbox.value) if checkbox.checked else prevValue = form.dataset.lastValue input = form.querySelector('.js-account-edit__input') if input.type == 'checkbox' value = input.checked else value = input.value.trim() { value, prevValue } saved: (el) => el.dataset.accountEditState = 'saved' el.savedTimeout = Timeout.set 3000, => @clearState el saving: (el) => el.dataset.accountEditState = 'saving' abortUpdate: (form) => Timeout.clear form.savedTimeout form.updating?.abort() @clearState form update: (form) => { value, prevValue } = @getValue(form) return @clearState(form) if value == prevValue form.dataset.lastValue = value url = form.dataset.url ? laroute.route('account.update') input = form.querySelector('.js-account-edit__input') field = form.dataset.field ? input.name form.updating = $.ajax url, method: 'PUT' data: "#{field}": value .done => @saved form $(form).trigger 'ajax:success' .fail (xhr, status) => return if status == 'abort' form.lastValue = prevValue @clearState form $(form).trigger 'ajax:error', [xhr, status]
176259
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @AccountEdit constructor: -> $(document).on 'input change', '.js-account-edit', @initializeUpdate $(document).on 'ajax:error', '.js-account-edit', @ajaxError $(document).on 'ajax:send', '.js-account-edit', @ajaxSaving $(document).on 'ajax:success', '.js-account-edit', @ajaxSaved initializeUpdate: (e) => form = e.currentTarget return if form.dataset.accountEditAutoSubmit != '1' @abortUpdate form @saving form form.debouncedUpdate ?= _.debounce @update, 1000 form.debouncedUpdate form ajaxError: (e) => @clearState e.currentTarget ajaxSaving: (e) => @saving e.currentTarget ajaxSaved: (e) => @saved e.currentTarget clearState: (el) => el.dataset.accountEditState = '' getValue: (form) -> if form.dataset.accountEditType == 'array' prevValue = null value = [''] for checkbox in form.querySelectorAll('input') value.push(checkbox.value) if checkbox.checked else prevValue = form.dataset.lastValue input = form.querySelector('.js-account-edit__input') if input.type == 'checkbox' value = input.checked else value = input.value.trim() { value, prevValue } saved: (el) => el.dataset.accountEditState = 'saved' el.savedTimeout = Timeout.set 3000, => @clearState el saving: (el) => el.dataset.accountEditState = 'saving' abortUpdate: (form) => Timeout.clear form.savedTimeout form.updating?.abort() @clearState form update: (form) => { value, prevValue } = @getValue(form) return @clearState(form) if value == prevValue form.dataset.lastValue = value url = form.dataset.url ? laroute.route('account.update') input = form.querySelector('.js-account-edit__input') field = form.dataset.field ? input.name form.updating = $.ajax url, method: 'PUT' data: "#{field}": value .done => @saved form $(form).trigger 'ajax:success' .fail (xhr, status) => return if status == 'abort' form.lastValue = prevValue @clearState form $(form).trigger 'ajax:error', [xhr, status]
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @AccountEdit constructor: -> $(document).on 'input change', '.js-account-edit', @initializeUpdate $(document).on 'ajax:error', '.js-account-edit', @ajaxError $(document).on 'ajax:send', '.js-account-edit', @ajaxSaving $(document).on 'ajax:success', '.js-account-edit', @ajaxSaved initializeUpdate: (e) => form = e.currentTarget return if form.dataset.accountEditAutoSubmit != '1' @abortUpdate form @saving form form.debouncedUpdate ?= _.debounce @update, 1000 form.debouncedUpdate form ajaxError: (e) => @clearState e.currentTarget ajaxSaving: (e) => @saving e.currentTarget ajaxSaved: (e) => @saved e.currentTarget clearState: (el) => el.dataset.accountEditState = '' getValue: (form) -> if form.dataset.accountEditType == 'array' prevValue = null value = [''] for checkbox in form.querySelectorAll('input') value.push(checkbox.value) if checkbox.checked else prevValue = form.dataset.lastValue input = form.querySelector('.js-account-edit__input') if input.type == 'checkbox' value = input.checked else value = input.value.trim() { value, prevValue } saved: (el) => el.dataset.accountEditState = 'saved' el.savedTimeout = Timeout.set 3000, => @clearState el saving: (el) => el.dataset.accountEditState = 'saving' abortUpdate: (form) => Timeout.clear form.savedTimeout form.updating?.abort() @clearState form update: (form) => { value, prevValue } = @getValue(form) return @clearState(form) if value == prevValue form.dataset.lastValue = value url = form.dataset.url ? laroute.route('account.update') input = form.querySelector('.js-account-edit__input') field = form.dataset.field ? input.name form.updating = $.ajax url, method: 'PUT' data: "#{field}": value .done => @saved form $(form).trigger 'ajax:success' .fail (xhr, status) => return if status == 'abort' form.lastValue = prevValue @clearState form $(form).trigger 'ajax:error', [xhr, status]
[ { "context": " }\r\n ]\r\n }\r\n]\r\nconfig = [\r\n {\r\n \"name\": \"AAA\",\r\n \"operations\": [\r\n {\r\n \"type\": ", "end": 4239, "score": 0.5278414487838745, "start": 4236, "tag": "NAME", "value": "AAA" }, { "context": "\r\n }\r\n ]\r\n },\r\n {\r\n \"name\": \"bathroom_count\",\r\n \"operations\": [\r\n {\r\n \"xpath\":", "end": 7829, "score": 0.736225962638855, "start": 7824, "tag": "USERNAME", "value": "count" }, { "context": "\\\\sbath\"\r\n }\r\n ]\r\n },\r\n {\r\n \"name\": \"contact\",\r\n \"operations\": [\r\n {\r\n \"xpath\":", "end": 8081, "score": 0.9504547119140625, "start": 8074, "tag": "NAME", "value": "contact" }, { "context": "by:(.*)\"\r\n }\r\n ]\r\n },\r\n {\r\n \"name\": \"additional_desc\",\r\n \"operations\": [\r\n {\r\n \"xp", "end": 8332, "score": 0.6440227627754211, "start": 8322, "tag": "NAME", "value": "additional" } ]
src/test/test.general.coffee
c301/declarative-parser
0
"use strict" default_config = [ { "name": "contact_telephone", "operations": { "valName": "phone" } }, { "name": "contact_email", "operations": { "valName": "email" } }, { "name": "heading", "operations": { "valName": "title" } }, { "name": "street", "operations": { "valName": "street_address" } }, { "name":"currency", "value":"USD" }, { "name":"property_type", "value":"apartment" }, { "name":"building_sqft", "value":"" }, { "name":"furnished", "value": 0 }, { "name":"relationship", "value": 0 }, { "name":"show_on_map", "value":"Y" }, { "name":"receive_emails", "value":"N" }, { "name":"pet_policy", "value":"2" }, { "name":"bathroom_count", "value":"1" }, { "name":"bedroom_count", "value":"1" }, { "name":"stored_city", "operations":[ { "final":"true", "storedName":"kijijiCity" }, { "final":"true", "type":"stored", "name":"craigslistCity" }, { "final":"true", "type":"stored", "name":"usedeverywhereCity" }, { "final":"true", "type":"stored", "name":"ebayclassifiedsCity" }, { "final":"true", "type":"stored", "name":"gottarentCity" }, { "final":"true", "type":"stored", "name":"viewitCity" }, { "final":"true", "type":"stored", "name":"zillowCity" }, { "final":"true", "type":"stored", "name":"freerentalsiteCity" }, { "final":"true", "type":"stored", "name":"sortopiaCity" } ] }, { "name":"location", "operations":[ { "type":"parsed_val", "name":"address" } ] }, { "name":"street_address", "operations":[ { "type":"parsed_val", "name":"address" } ] }, { "name":"street_number", "operations":[ { "type":"parsed_val", "name":"address" }, { "regex":"(\\d+)" } ] }, { "name":"street_name", "operations":[ { "type":"parsed_val", "name":"address" }, { "opName":"street_regex" } ] }, { "name":"city", "operations":[ { "valName":"stored_city" }, { "regex": "^(.*?)," } ] }, { "name":"state", "operations":[ { "valName":"stored_city" }, { "regex": "^.*,\\s(.*)," } ] }, { "name":"country", "operations":[ { "valName":"stored_city" }, { "regex": "^.*,\\s.*,\\s(.*)" } ] }, { "name":"signature", "operations":[ { "storedName":"listingSignature" } ] }, { "name":"want_email", "operations":[ { "type":"stored", "name":"usedeverywhereReceiveEmail", "postprocessing":[ { "type":"switchOf", "flag":{ "type":"equal", "value":"true" }, "positive":"Y", "negative":"N" } ] } ] }, { "name":"description", "operations":[ { "type":"concatenation", "glue":"", "parts":[ { "valName":"description_text" }, { "valName":"contact", "preffix":"\nContact:" }, { "valName":"phone", "preffix":"\nTelephone:" }, { "valName":"available_date", "preffix":"\n" }, { "valName":"signature" } ] } ] } ] config = [ { "name": "AAA", "operations": [ { "type": "wait", "delay": "2000" }, { "valName": "title_text" } ] }, { "name": "random", "operations": { "type": "randomInt", "from": 1, "to": 99 } }, { "name": "listing_link", "operations": [ { "type": "current_document" }, { "attribute": "location" }, { "attribute": "href" } ] }, { "name": "managed_by", "operations": { "xpath": "normalize-space(string(.//div[@id='manager-body']/div[@id='managed-by']))" } } , { "name": "viewing_and_info", "operations": { "xpath": "normalize-space(string(.//div[@id='manager-body']/div[@id='viewings-and-info']))" } }, { "name": "amenities_right_html", "operations": [ { "xpath": ".//div[@id='amenities-holder']/div[@id='amenities-body']/ul[@class='right']/li" }, { "attribute": "textContent", "glue": "</li><li>", "preffix": "<li>", "suffix": "</li>" } ] }, { "name": "amenities_left_html", "operations": [ { "xpath": ".//div[@id='amenities-holder']/div[@id='amenities-body']/ul[@class='left']/li" }, { "attribute": "textContent", "glue": "</li><li>", "preffix": "<li>", "suffix": "</li>" } ] }, { "name": "main_photo_url", "operations": [ { "xpath": ".//div[@id='photo-holder']/img[@id='listing-photo']", "num_in_array": "0" }, { "attribute": "src" } ] }, { "name": "title_text", "operations": [ { "xpath": "normalize-space(string(//*[@id='listing-wrapper']/h1))" } ] } , { "name": "bedroom_count_text", "operations": { "type": "switchOf", "value": { "valName": "bedroom_count" }, "flag": { "type": "equal", "value": "0" }, "positive": "Bachelor", "negative": { "valName": "bedroom_count", "default": "1", "suffix": "-bedrooms" } } }, { "name": "title", "operations": [ { "type": "concatenation", "glue": ", ", "parts": [ { "valName": "title_text" }, { "valName": "bedroom_count_text" }, { "valName": "bathroom_count", "default": "1", "suffix": " bathrooms" } ] } ] }, { "name": "price", "default": "402", "operations": [ { "xpath": "string(//*[@id='vacancies-body']/div[1]/div[1])" }, { "type": "regex", "regex": "\\$(\\d+\\.?\\d+)" } ] }, { "name": "bedroom_count", "operations": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/div[1]/span[1]))" }, { "type": "switchOf", "flag": { "type": "equal", "is_regex": true, "value": "Bachelor" }, "positive": "0", "negative": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/div[1]/span[1]))" }, { "type": "regex", "regex": "(\\d+)" } ] } ] }, { "name": "bathroom_count", "operations": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/ul/li[contains(text(),'bathroom')]))" }, { "regex": "([\\d\\.]+)\\sbath" } ] }, { "name": "contact", "operations": [ { "xpath": "translate(normalize-space(string(//*[@id='managed-by'])), '', '')" }, { "type": "regex", "regex": "Managed by:(.*)" } ] }, { "name": "additional_desc", "operations": [ { "xpath": ".//*[@class='left']/li", }, { "attribute": "textContent", "glue": "|", "preffix": "++", "suffix": "++", "normalize_space": true } ] }, { "name": "description_text", "operations": [ { "xpath": "normalize-space(string(//*[@id='description-body']))" } ] }, { "name": "description_raw", "operations": [ { "xpath": "//*[@id='description-body']", "num_in_array": "0" }, { "attribute": "innerHTML" } ] }, { "name": "phone", "operations": [ { "xpath": "translate( normalize-space(string(//*[@id='viewings-and-info'])),'For viewings & information please call:', '')" }, { "type": "regex", "regex": "((\\(\\d{3}\\)|\\d{3}-)?\\s*\\d{3}-\\d{4}|\\d{3}\\.|-\\d{3}\\.|-\\d{4})" } ] }, { "name": "address", "operations": [ { "type": "concatenation", "glue": ", ", "parts": [ { "valName": "street_address" }, { "valName": "city" }, { "type": "concatenation", "glue": " ", "parts": [ { "valName": "postal_code" }, { "valName": "state" } ] }, { "valName": "country" } ] } ] }, { "name": "location", "operations": { "valName": "address" } }, { "name": "street_address", "operations": [ {"xpath": "string(.//span[@itemprop='streetAddress'])"} ] }, { "name": "city", "default": "Victoria", "operations": [ {"xpath": "string(.//meta[@itemprop='addressLocality']/@content)"}, {"regex": "(.+?),"} ] }, { "name": "state", "default": "BC", "operations": [ {"xpath": "string(.//meta[@itemprop='addressRegion']/@content)"} ] }, { "name": "postal_code", "operations": [ {"xpath": "string(.//meta[@itemprop='postalCode']/@content)"} ] }, { "name": "country", "operations": [ {"xpath": "string(.//meta[@itemprop='addressCountry']/@content)"} ] }, { "name": "description_html", "operations": { "template": "<h3>{:title_text:}</h3> <b>Price:</b> ${:price:} <br/> <br/> {:additional_desc:} {:description_raw:} <br/> <br/> <b>Building Amenities:</b> <ul> {:amenities_left_html:} {:amenities_right_html:} </ul> <b>{:managed_by:}</b> <br/> <b>Phone: {:phone:}</b>" } }, { "name": "description", "operations": [ { "type": "concatenation", "glue": "", "parts": [ { "valName": "description_text", "suffix": "\n\n" }, { "preffix": "\nBuilding Manager: ", "valName": "contact" }, { "preffix": "\nTelephone: ", "valName": "phone" }, { "valName": "signature", "preffix": "\n\n\n" } ] } ] } ] describe "General parsing", ()-> htmlText = '' # before (done)-> # @timeout 30000 # console.log 'get remote doc' # $.get "http://www.devonprop.com/victoria-rental-listings/listing/?id=1661", (res)-> # console.log '===============================', res # htmlText = res.responseText # done() # it "Get remote doc and parse", (done)-> # @timeout 5000 # parser = new Parser( htmlText ) # parser.parse( config, default_config ).then (res)-> # console.log res # if res.title_text != "Braemore Manor - 1118 Balmoral Road" # done(new Error "Wrong parsing result") # else # done() it "Pass custom operation", (done)-> @timeout 5000 parser = new Parser() parser.addOperations( { concatenation1: ()-> parts = @config.parts glue = @config.glue || "" toWait = [] result = [] d = Q.defer() for part in parts do ( part ) => toWait.push( @createOperation part .evaluate().then (res)-> if res result.push res ) Q.allSettled toWait .then ()=> d.resolve result.join glue d.promise } ) parser.parse( [{ "name": "address", "operations": [ { "type": "concatenation1", "glue": ", ", "parts": [ { "value": "Moscow" }, { "value": "Red Square" }, { "type": "concatenation", "glue": " ", "parts": [ { "value": "433000" }, { "value": "JC" } ] } ] } ] }] ).then (res)-> if res.address != "Moscow, Red Square, 433000 JC" done(new Error "Wrong parsing result") else done() it "Document as string", ()-> config = [ { name : "price", operations: [ { type: "xpath", xpath: "string(.//*[@class='price'])" } ] } ] parser = new Parser("<div class='price'>$302</div>") parser.parse( config ).then (res)-> expect res .to.have.a.property "price", "$302" it "Parse. Value in short form. Operations was ommited", ()-> config = [ { name : "price", default: "" } ] parser = new Parser() parser.parse( config ).then (res)-> expect res .to.have.a.property "price", Operation.EMPTY_VALUE it "Parse", ()-> config = [ { name : "price", operations: [ { type: "xpath", xpath: "string(.//*[@class='price'])" } ] } ] parser = new Parser() parser.parse( config ).then (res)-> expect res .to.have.a.property "price", "$ 301" it "Pass custom decorators", (done)-> @timeout 30000 parser = new Parser() parser.addDecorators( { num_in_array_custom: ( value )-> if value instanceof Array value[@config.num_in_array_custom] else value } ) parser.parse( [ { name : "price", operations: [ { type: "xpath", xpath: ".//*[@class='price']" }, { attribute: "textContent", "num_in_array_custom": 0 } ] } ] ).then (res)-> if res.price != "$ 301" done(new Error "Wrong parsing result") else done() it "Parser hooks", (done)-> @timeout 3000 parser = new Parser({ parseHooks : { price : { after: (val)-> console.log( "after hook", val ) if val == "$ 301" "hello" else val } } }) parser.parse( [ { name : "price", operations: [ { type: "xpath", xpath: ".//*[@class='price']" }, { attribute: "textContent", "num_in_array": 0 } ] } ] ).then (res)-> if res.price != "hello" done(new Error "Wrong parsing result") else done()
193363
"use strict" default_config = [ { "name": "contact_telephone", "operations": { "valName": "phone" } }, { "name": "contact_email", "operations": { "valName": "email" } }, { "name": "heading", "operations": { "valName": "title" } }, { "name": "street", "operations": { "valName": "street_address" } }, { "name":"currency", "value":"USD" }, { "name":"property_type", "value":"apartment" }, { "name":"building_sqft", "value":"" }, { "name":"furnished", "value": 0 }, { "name":"relationship", "value": 0 }, { "name":"show_on_map", "value":"Y" }, { "name":"receive_emails", "value":"N" }, { "name":"pet_policy", "value":"2" }, { "name":"bathroom_count", "value":"1" }, { "name":"bedroom_count", "value":"1" }, { "name":"stored_city", "operations":[ { "final":"true", "storedName":"kijijiCity" }, { "final":"true", "type":"stored", "name":"craigslistCity" }, { "final":"true", "type":"stored", "name":"usedeverywhereCity" }, { "final":"true", "type":"stored", "name":"ebayclassifiedsCity" }, { "final":"true", "type":"stored", "name":"gottarentCity" }, { "final":"true", "type":"stored", "name":"viewitCity" }, { "final":"true", "type":"stored", "name":"zillowCity" }, { "final":"true", "type":"stored", "name":"freerentalsiteCity" }, { "final":"true", "type":"stored", "name":"sortopiaCity" } ] }, { "name":"location", "operations":[ { "type":"parsed_val", "name":"address" } ] }, { "name":"street_address", "operations":[ { "type":"parsed_val", "name":"address" } ] }, { "name":"street_number", "operations":[ { "type":"parsed_val", "name":"address" }, { "regex":"(\\d+)" } ] }, { "name":"street_name", "operations":[ { "type":"parsed_val", "name":"address" }, { "opName":"street_regex" } ] }, { "name":"city", "operations":[ { "valName":"stored_city" }, { "regex": "^(.*?)," } ] }, { "name":"state", "operations":[ { "valName":"stored_city" }, { "regex": "^.*,\\s(.*)," } ] }, { "name":"country", "operations":[ { "valName":"stored_city" }, { "regex": "^.*,\\s.*,\\s(.*)" } ] }, { "name":"signature", "operations":[ { "storedName":"listingSignature" } ] }, { "name":"want_email", "operations":[ { "type":"stored", "name":"usedeverywhereReceiveEmail", "postprocessing":[ { "type":"switchOf", "flag":{ "type":"equal", "value":"true" }, "positive":"Y", "negative":"N" } ] } ] }, { "name":"description", "operations":[ { "type":"concatenation", "glue":"", "parts":[ { "valName":"description_text" }, { "valName":"contact", "preffix":"\nContact:" }, { "valName":"phone", "preffix":"\nTelephone:" }, { "valName":"available_date", "preffix":"\n" }, { "valName":"signature" } ] } ] } ] config = [ { "name": "<NAME>", "operations": [ { "type": "wait", "delay": "2000" }, { "valName": "title_text" } ] }, { "name": "random", "operations": { "type": "randomInt", "from": 1, "to": 99 } }, { "name": "listing_link", "operations": [ { "type": "current_document" }, { "attribute": "location" }, { "attribute": "href" } ] }, { "name": "managed_by", "operations": { "xpath": "normalize-space(string(.//div[@id='manager-body']/div[@id='managed-by']))" } } , { "name": "viewing_and_info", "operations": { "xpath": "normalize-space(string(.//div[@id='manager-body']/div[@id='viewings-and-info']))" } }, { "name": "amenities_right_html", "operations": [ { "xpath": ".//div[@id='amenities-holder']/div[@id='amenities-body']/ul[@class='right']/li" }, { "attribute": "textContent", "glue": "</li><li>", "preffix": "<li>", "suffix": "</li>" } ] }, { "name": "amenities_left_html", "operations": [ { "xpath": ".//div[@id='amenities-holder']/div[@id='amenities-body']/ul[@class='left']/li" }, { "attribute": "textContent", "glue": "</li><li>", "preffix": "<li>", "suffix": "</li>" } ] }, { "name": "main_photo_url", "operations": [ { "xpath": ".//div[@id='photo-holder']/img[@id='listing-photo']", "num_in_array": "0" }, { "attribute": "src" } ] }, { "name": "title_text", "operations": [ { "xpath": "normalize-space(string(//*[@id='listing-wrapper']/h1))" } ] } , { "name": "bedroom_count_text", "operations": { "type": "switchOf", "value": { "valName": "bedroom_count" }, "flag": { "type": "equal", "value": "0" }, "positive": "Bachelor", "negative": { "valName": "bedroom_count", "default": "1", "suffix": "-bedrooms" } } }, { "name": "title", "operations": [ { "type": "concatenation", "glue": ", ", "parts": [ { "valName": "title_text" }, { "valName": "bedroom_count_text" }, { "valName": "bathroom_count", "default": "1", "suffix": " bathrooms" } ] } ] }, { "name": "price", "default": "402", "operations": [ { "xpath": "string(//*[@id='vacancies-body']/div[1]/div[1])" }, { "type": "regex", "regex": "\\$(\\d+\\.?\\d+)" } ] }, { "name": "bedroom_count", "operations": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/div[1]/span[1]))" }, { "type": "switchOf", "flag": { "type": "equal", "is_regex": true, "value": "Bachelor" }, "positive": "0", "negative": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/div[1]/span[1]))" }, { "type": "regex", "regex": "(\\d+)" } ] } ] }, { "name": "bathroom_count", "operations": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/ul/li[contains(text(),'bathroom')]))" }, { "regex": "([\\d\\.]+)\\sbath" } ] }, { "name": "<NAME>", "operations": [ { "xpath": "translate(normalize-space(string(//*[@id='managed-by'])), '', '')" }, { "type": "regex", "regex": "Managed by:(.*)" } ] }, { "name": "<NAME>_desc", "operations": [ { "xpath": ".//*[@class='left']/li", }, { "attribute": "textContent", "glue": "|", "preffix": "++", "suffix": "++", "normalize_space": true } ] }, { "name": "description_text", "operations": [ { "xpath": "normalize-space(string(//*[@id='description-body']))" } ] }, { "name": "description_raw", "operations": [ { "xpath": "//*[@id='description-body']", "num_in_array": "0" }, { "attribute": "innerHTML" } ] }, { "name": "phone", "operations": [ { "xpath": "translate( normalize-space(string(//*[@id='viewings-and-info'])),'For viewings & information please call:', '')" }, { "type": "regex", "regex": "((\\(\\d{3}\\)|\\d{3}-)?\\s*\\d{3}-\\d{4}|\\d{3}\\.|-\\d{3}\\.|-\\d{4})" } ] }, { "name": "address", "operations": [ { "type": "concatenation", "glue": ", ", "parts": [ { "valName": "street_address" }, { "valName": "city" }, { "type": "concatenation", "glue": " ", "parts": [ { "valName": "postal_code" }, { "valName": "state" } ] }, { "valName": "country" } ] } ] }, { "name": "location", "operations": { "valName": "address" } }, { "name": "street_address", "operations": [ {"xpath": "string(.//span[@itemprop='streetAddress'])"} ] }, { "name": "city", "default": "Victoria", "operations": [ {"xpath": "string(.//meta[@itemprop='addressLocality']/@content)"}, {"regex": "(.+?),"} ] }, { "name": "state", "default": "BC", "operations": [ {"xpath": "string(.//meta[@itemprop='addressRegion']/@content)"} ] }, { "name": "postal_code", "operations": [ {"xpath": "string(.//meta[@itemprop='postalCode']/@content)"} ] }, { "name": "country", "operations": [ {"xpath": "string(.//meta[@itemprop='addressCountry']/@content)"} ] }, { "name": "description_html", "operations": { "template": "<h3>{:title_text:}</h3> <b>Price:</b> ${:price:} <br/> <br/> {:additional_desc:} {:description_raw:} <br/> <br/> <b>Building Amenities:</b> <ul> {:amenities_left_html:} {:amenities_right_html:} </ul> <b>{:managed_by:}</b> <br/> <b>Phone: {:phone:}</b>" } }, { "name": "description", "operations": [ { "type": "concatenation", "glue": "", "parts": [ { "valName": "description_text", "suffix": "\n\n" }, { "preffix": "\nBuilding Manager: ", "valName": "contact" }, { "preffix": "\nTelephone: ", "valName": "phone" }, { "valName": "signature", "preffix": "\n\n\n" } ] } ] } ] describe "General parsing", ()-> htmlText = '' # before (done)-> # @timeout 30000 # console.log 'get remote doc' # $.get "http://www.devonprop.com/victoria-rental-listings/listing/?id=1661", (res)-> # console.log '===============================', res # htmlText = res.responseText # done() # it "Get remote doc and parse", (done)-> # @timeout 5000 # parser = new Parser( htmlText ) # parser.parse( config, default_config ).then (res)-> # console.log res # if res.title_text != "Braemore Manor - 1118 Balmoral Road" # done(new Error "Wrong parsing result") # else # done() it "Pass custom operation", (done)-> @timeout 5000 parser = new Parser() parser.addOperations( { concatenation1: ()-> parts = @config.parts glue = @config.glue || "" toWait = [] result = [] d = Q.defer() for part in parts do ( part ) => toWait.push( @createOperation part .evaluate().then (res)-> if res result.push res ) Q.allSettled toWait .then ()=> d.resolve result.join glue d.promise } ) parser.parse( [{ "name": "address", "operations": [ { "type": "concatenation1", "glue": ", ", "parts": [ { "value": "Moscow" }, { "value": "Red Square" }, { "type": "concatenation", "glue": " ", "parts": [ { "value": "433000" }, { "value": "JC" } ] } ] } ] }] ).then (res)-> if res.address != "Moscow, Red Square, 433000 JC" done(new Error "Wrong parsing result") else done() it "Document as string", ()-> config = [ { name : "price", operations: [ { type: "xpath", xpath: "string(.//*[@class='price'])" } ] } ] parser = new Parser("<div class='price'>$302</div>") parser.parse( config ).then (res)-> expect res .to.have.a.property "price", "$302" it "Parse. Value in short form. Operations was ommited", ()-> config = [ { name : "price", default: "" } ] parser = new Parser() parser.parse( config ).then (res)-> expect res .to.have.a.property "price", Operation.EMPTY_VALUE it "Parse", ()-> config = [ { name : "price", operations: [ { type: "xpath", xpath: "string(.//*[@class='price'])" } ] } ] parser = new Parser() parser.parse( config ).then (res)-> expect res .to.have.a.property "price", "$ 301" it "Pass custom decorators", (done)-> @timeout 30000 parser = new Parser() parser.addDecorators( { num_in_array_custom: ( value )-> if value instanceof Array value[@config.num_in_array_custom] else value } ) parser.parse( [ { name : "price", operations: [ { type: "xpath", xpath: ".//*[@class='price']" }, { attribute: "textContent", "num_in_array_custom": 0 } ] } ] ).then (res)-> if res.price != "$ 301" done(new Error "Wrong parsing result") else done() it "Parser hooks", (done)-> @timeout 3000 parser = new Parser({ parseHooks : { price : { after: (val)-> console.log( "after hook", val ) if val == "$ 301" "hello" else val } } }) parser.parse( [ { name : "price", operations: [ { type: "xpath", xpath: ".//*[@class='price']" }, { attribute: "textContent", "num_in_array": 0 } ] } ] ).then (res)-> if res.price != "hello" done(new Error "Wrong parsing result") else done()
true
"use strict" default_config = [ { "name": "contact_telephone", "operations": { "valName": "phone" } }, { "name": "contact_email", "operations": { "valName": "email" } }, { "name": "heading", "operations": { "valName": "title" } }, { "name": "street", "operations": { "valName": "street_address" } }, { "name":"currency", "value":"USD" }, { "name":"property_type", "value":"apartment" }, { "name":"building_sqft", "value":"" }, { "name":"furnished", "value": 0 }, { "name":"relationship", "value": 0 }, { "name":"show_on_map", "value":"Y" }, { "name":"receive_emails", "value":"N" }, { "name":"pet_policy", "value":"2" }, { "name":"bathroom_count", "value":"1" }, { "name":"bedroom_count", "value":"1" }, { "name":"stored_city", "operations":[ { "final":"true", "storedName":"kijijiCity" }, { "final":"true", "type":"stored", "name":"craigslistCity" }, { "final":"true", "type":"stored", "name":"usedeverywhereCity" }, { "final":"true", "type":"stored", "name":"ebayclassifiedsCity" }, { "final":"true", "type":"stored", "name":"gottarentCity" }, { "final":"true", "type":"stored", "name":"viewitCity" }, { "final":"true", "type":"stored", "name":"zillowCity" }, { "final":"true", "type":"stored", "name":"freerentalsiteCity" }, { "final":"true", "type":"stored", "name":"sortopiaCity" } ] }, { "name":"location", "operations":[ { "type":"parsed_val", "name":"address" } ] }, { "name":"street_address", "operations":[ { "type":"parsed_val", "name":"address" } ] }, { "name":"street_number", "operations":[ { "type":"parsed_val", "name":"address" }, { "regex":"(\\d+)" } ] }, { "name":"street_name", "operations":[ { "type":"parsed_val", "name":"address" }, { "opName":"street_regex" } ] }, { "name":"city", "operations":[ { "valName":"stored_city" }, { "regex": "^(.*?)," } ] }, { "name":"state", "operations":[ { "valName":"stored_city" }, { "regex": "^.*,\\s(.*)," } ] }, { "name":"country", "operations":[ { "valName":"stored_city" }, { "regex": "^.*,\\s.*,\\s(.*)" } ] }, { "name":"signature", "operations":[ { "storedName":"listingSignature" } ] }, { "name":"want_email", "operations":[ { "type":"stored", "name":"usedeverywhereReceiveEmail", "postprocessing":[ { "type":"switchOf", "flag":{ "type":"equal", "value":"true" }, "positive":"Y", "negative":"N" } ] } ] }, { "name":"description", "operations":[ { "type":"concatenation", "glue":"", "parts":[ { "valName":"description_text" }, { "valName":"contact", "preffix":"\nContact:" }, { "valName":"phone", "preffix":"\nTelephone:" }, { "valName":"available_date", "preffix":"\n" }, { "valName":"signature" } ] } ] } ] config = [ { "name": "PI:NAME:<NAME>END_PI", "operations": [ { "type": "wait", "delay": "2000" }, { "valName": "title_text" } ] }, { "name": "random", "operations": { "type": "randomInt", "from": 1, "to": 99 } }, { "name": "listing_link", "operations": [ { "type": "current_document" }, { "attribute": "location" }, { "attribute": "href" } ] }, { "name": "managed_by", "operations": { "xpath": "normalize-space(string(.//div[@id='manager-body']/div[@id='managed-by']))" } } , { "name": "viewing_and_info", "operations": { "xpath": "normalize-space(string(.//div[@id='manager-body']/div[@id='viewings-and-info']))" } }, { "name": "amenities_right_html", "operations": [ { "xpath": ".//div[@id='amenities-holder']/div[@id='amenities-body']/ul[@class='right']/li" }, { "attribute": "textContent", "glue": "</li><li>", "preffix": "<li>", "suffix": "</li>" } ] }, { "name": "amenities_left_html", "operations": [ { "xpath": ".//div[@id='amenities-holder']/div[@id='amenities-body']/ul[@class='left']/li" }, { "attribute": "textContent", "glue": "</li><li>", "preffix": "<li>", "suffix": "</li>" } ] }, { "name": "main_photo_url", "operations": [ { "xpath": ".//div[@id='photo-holder']/img[@id='listing-photo']", "num_in_array": "0" }, { "attribute": "src" } ] }, { "name": "title_text", "operations": [ { "xpath": "normalize-space(string(//*[@id='listing-wrapper']/h1))" } ] } , { "name": "bedroom_count_text", "operations": { "type": "switchOf", "value": { "valName": "bedroom_count" }, "flag": { "type": "equal", "value": "0" }, "positive": "Bachelor", "negative": { "valName": "bedroom_count", "default": "1", "suffix": "-bedrooms" } } }, { "name": "title", "operations": [ { "type": "concatenation", "glue": ", ", "parts": [ { "valName": "title_text" }, { "valName": "bedroom_count_text" }, { "valName": "bathroom_count", "default": "1", "suffix": " bathrooms" } ] } ] }, { "name": "price", "default": "402", "operations": [ { "xpath": "string(//*[@id='vacancies-body']/div[1]/div[1])" }, { "type": "regex", "regex": "\\$(\\d+\\.?\\d+)" } ] }, { "name": "bedroom_count", "operations": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/div[1]/span[1]))" }, { "type": "switchOf", "flag": { "type": "equal", "is_regex": true, "value": "Bachelor" }, "positive": "0", "negative": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/div[1]/span[1]))" }, { "type": "regex", "regex": "(\\d+)" } ] } ] }, { "name": "bathroom_count", "operations": [ { "xpath": "normalize-space(string(//*[@id='vacancies-body']/div[1]/ul/li[contains(text(),'bathroom')]))" }, { "regex": "([\\d\\.]+)\\sbath" } ] }, { "name": "PI:NAME:<NAME>END_PI", "operations": [ { "xpath": "translate(normalize-space(string(//*[@id='managed-by'])), '', '')" }, { "type": "regex", "regex": "Managed by:(.*)" } ] }, { "name": "PI:NAME:<NAME>END_PI_desc", "operations": [ { "xpath": ".//*[@class='left']/li", }, { "attribute": "textContent", "glue": "|", "preffix": "++", "suffix": "++", "normalize_space": true } ] }, { "name": "description_text", "operations": [ { "xpath": "normalize-space(string(//*[@id='description-body']))" } ] }, { "name": "description_raw", "operations": [ { "xpath": "//*[@id='description-body']", "num_in_array": "0" }, { "attribute": "innerHTML" } ] }, { "name": "phone", "operations": [ { "xpath": "translate( normalize-space(string(//*[@id='viewings-and-info'])),'For viewings & information please call:', '')" }, { "type": "regex", "regex": "((\\(\\d{3}\\)|\\d{3}-)?\\s*\\d{3}-\\d{4}|\\d{3}\\.|-\\d{3}\\.|-\\d{4})" } ] }, { "name": "address", "operations": [ { "type": "concatenation", "glue": ", ", "parts": [ { "valName": "street_address" }, { "valName": "city" }, { "type": "concatenation", "glue": " ", "parts": [ { "valName": "postal_code" }, { "valName": "state" } ] }, { "valName": "country" } ] } ] }, { "name": "location", "operations": { "valName": "address" } }, { "name": "street_address", "operations": [ {"xpath": "string(.//span[@itemprop='streetAddress'])"} ] }, { "name": "city", "default": "Victoria", "operations": [ {"xpath": "string(.//meta[@itemprop='addressLocality']/@content)"}, {"regex": "(.+?),"} ] }, { "name": "state", "default": "BC", "operations": [ {"xpath": "string(.//meta[@itemprop='addressRegion']/@content)"} ] }, { "name": "postal_code", "operations": [ {"xpath": "string(.//meta[@itemprop='postalCode']/@content)"} ] }, { "name": "country", "operations": [ {"xpath": "string(.//meta[@itemprop='addressCountry']/@content)"} ] }, { "name": "description_html", "operations": { "template": "<h3>{:title_text:}</h3> <b>Price:</b> ${:price:} <br/> <br/> {:additional_desc:} {:description_raw:} <br/> <br/> <b>Building Amenities:</b> <ul> {:amenities_left_html:} {:amenities_right_html:} </ul> <b>{:managed_by:}</b> <br/> <b>Phone: {:phone:}</b>" } }, { "name": "description", "operations": [ { "type": "concatenation", "glue": "", "parts": [ { "valName": "description_text", "suffix": "\n\n" }, { "preffix": "\nBuilding Manager: ", "valName": "contact" }, { "preffix": "\nTelephone: ", "valName": "phone" }, { "valName": "signature", "preffix": "\n\n\n" } ] } ] } ] describe "General parsing", ()-> htmlText = '' # before (done)-> # @timeout 30000 # console.log 'get remote doc' # $.get "http://www.devonprop.com/victoria-rental-listings/listing/?id=1661", (res)-> # console.log '===============================', res # htmlText = res.responseText # done() # it "Get remote doc and parse", (done)-> # @timeout 5000 # parser = new Parser( htmlText ) # parser.parse( config, default_config ).then (res)-> # console.log res # if res.title_text != "Braemore Manor - 1118 Balmoral Road" # done(new Error "Wrong parsing result") # else # done() it "Pass custom operation", (done)-> @timeout 5000 parser = new Parser() parser.addOperations( { concatenation1: ()-> parts = @config.parts glue = @config.glue || "" toWait = [] result = [] d = Q.defer() for part in parts do ( part ) => toWait.push( @createOperation part .evaluate().then (res)-> if res result.push res ) Q.allSettled toWait .then ()=> d.resolve result.join glue d.promise } ) parser.parse( [{ "name": "address", "operations": [ { "type": "concatenation1", "glue": ", ", "parts": [ { "value": "Moscow" }, { "value": "Red Square" }, { "type": "concatenation", "glue": " ", "parts": [ { "value": "433000" }, { "value": "JC" } ] } ] } ] }] ).then (res)-> if res.address != "Moscow, Red Square, 433000 JC" done(new Error "Wrong parsing result") else done() it "Document as string", ()-> config = [ { name : "price", operations: [ { type: "xpath", xpath: "string(.//*[@class='price'])" } ] } ] parser = new Parser("<div class='price'>$302</div>") parser.parse( config ).then (res)-> expect res .to.have.a.property "price", "$302" it "Parse. Value in short form. Operations was ommited", ()-> config = [ { name : "price", default: "" } ] parser = new Parser() parser.parse( config ).then (res)-> expect res .to.have.a.property "price", Operation.EMPTY_VALUE it "Parse", ()-> config = [ { name : "price", operations: [ { type: "xpath", xpath: "string(.//*[@class='price'])" } ] } ] parser = new Parser() parser.parse( config ).then (res)-> expect res .to.have.a.property "price", "$ 301" it "Pass custom decorators", (done)-> @timeout 30000 parser = new Parser() parser.addDecorators( { num_in_array_custom: ( value )-> if value instanceof Array value[@config.num_in_array_custom] else value } ) parser.parse( [ { name : "price", operations: [ { type: "xpath", xpath: ".//*[@class='price']" }, { attribute: "textContent", "num_in_array_custom": 0 } ] } ] ).then (res)-> if res.price != "$ 301" done(new Error "Wrong parsing result") else done() it "Parser hooks", (done)-> @timeout 3000 parser = new Parser({ parseHooks : { price : { after: (val)-> console.log( "after hook", val ) if val == "$ 301" "hello" else val } } }) parser.parse( [ { name : "price", operations: [ { type: "xpath", xpath: ".//*[@class='price']" }, { attribute: "textContent", "num_in_array": 0 } ] } ] ).then (res)-> if res.price != "hello" done(new Error "Wrong parsing result") else done()
[ { "context": "mountain3b.alpha = 0.4\n\n move = @game.add.tween(@mountain0a)\n move.to({x: -2000}, 31000, Phaser.Easing.Lin", "end": 2836, "score": 0.9990341067314148, "start": 2825, "tag": "USERNAME", "value": "@mountain0a" }, { "context": "ear.None, true, 0, 999)\n move = @game.add.tween(@mountain0b)\n move.to({x: 0}, 31000, Phaser.Easing.Linear.", "end": 2948, "score": 0.998794674873352, "start": 2937, "tag": "USERNAME", "value": "@mountain0b" }, { "context": "ar.None, true, 0, 999)\n\n move = @game.add.tween(@mountain1a)\n move.to({x: -2000}, 18000, Phaser.Easing.Lin", "end": 3057, "score": 0.9988369941711426, "start": 3046, "tag": "USERNAME", "value": "@mountain1a" }, { "context": "ear.None, true, 0, 999)\n move = @game.add.tween(@mountain1b)\n move.to({x: 0}, 18000, Phaser.Easing.Linear.", "end": 3169, "score": 0.9987508058547974, "start": 3158, "tag": "USERNAME", "value": "@mountain1b" }, { "context": "ar.None, true, 0, 999)\n\n move = @game.add.tween(@mountain2a)\n move.to({x: -2000}, 13000, Phaser.Easing.Lin", "end": 3278, "score": 0.9989282488822937, "start": 3267, "tag": "USERNAME", "value": "@mountain2a" }, { "context": "ear.None, true, 0, 999)\n move = @game.add.tween(@mountain2b)\n move.to({x: 0}, 13000, Phaser.Easing.Linear.", "end": 3390, "score": 0.9987374544143677, "start": 3379, "tag": "USERNAME", "value": "@mountain2b" }, { "context": "ar.None, true, 0, 999)\n\n move = @game.add.tween(@mountain3a)\n move.to({x: -2000}, 7000, Phaser.Easing.Line", "end": 3499, "score": 0.9977651834487915, "start": 3488, "tag": "USERNAME", "value": "@mountain3a" }, { "context": "ear.None, true, 0, 999)\n move = @game.add.tween(@mountain3b)\n move.to({x: 0}, 7000, Phaser.Easing.Linear.N", "end": 3610, "score": 0.9979242086410522, "start": 3599, "tag": "USERNAME", "value": "@mountain3b" }, { "context": ".body.allowGravity = false\n w = if obj.key == 'bomb' then 5 else 15\n h = w\n obj.body.setRectang", "end": 6514, "score": 0.8285514712333679, "start": 6510, "tag": "KEY", "value": "bomb" }, { "context": "s.stop()\n player.frame = if player.key == 'runner' then 4 else 2\n if !wasOnGround && player.onGr", "end": 7948, "score": 0.9653006196022034, "start": 7942, "tag": "KEY", "value": "runner" }, { "context": "nd\n player.play('run')\n if player.key == 'wolf' && player.x == player.target && player.onGround\n", "end": 8054, "score": 0.994353711605072, "start": 8050, "tag": "KEY", "value": "wolf" }, { "context": ".rnd.realInRange(0, 10000))\n if player.key == 'runner'\n @game.physics.overlap(player, @collect_gro", "end": 8366, "score": 0.9681214690208435, "start": 8360, "tag": "KEY", "value": "runner" }, { "context": ".forEachAlive (player) =>\n if player.key == 'runner'\n player.jump = true\n window.laggyd", "end": 8510, "score": 0.9748707413673401, "start": 8504, "tag": "KEY", "value": "runner" }, { "context": "r.body = null\n avatar.id = id\n avatar.name = name\n avatar.width = 60\n avatar.height = 60\n ", "end": 11882, "score": 0.9954992532730103, "start": 11878, "tag": "NAME", "value": "name" }, { "context": "\"#ffffff\"\n\n label = @game.add.text(x, 480, \"@#{name}\", style)\n label.x -= label.width / 2\n labe", "end": 12522, "score": 0.4485571086406708, "start": 12518, "tag": "USERNAME", "value": "name" }, { "context": "r\n player.jump = true\n\n destroy:->\n destroy(@tree0)\n destroy(@tree1)\n destroy(@tree2)\n dest", "end": 15549, "score": 0.9977593421936035, "start": 15543, "tag": "USERNAME", "value": "@tree0" }, { "context": "true\n\n destroy:->\n destroy(@tree0)\n destroy(@tree1)\n destroy(@tree2)\n destroy(@tree3)\n dest", "end": 15569, "score": 0.9966275095939636, "start": 15563, "tag": "USERNAME", "value": "@tree1" }, { "context": " destroy(@tree0)\n destroy(@tree1)\n destroy(@tree2)\n destroy(@tree3)\n destroy(@night)\n dest", "end": 15589, "score": 0.9961926937103271, "start": 15583, "tag": "USERNAME", "value": "@tree2" }, { "context": " destroy(@tree1)\n destroy(@tree2)\n destroy(@tree3)\n destroy(@night)\n destroy(@sky)\n destro", "end": 15609, "score": 0.9917795062065125, "start": 15603, "tag": "USERNAME", "value": "@tree3" }, { "context": " destroy(@tree2)\n destroy(@tree3)\n destroy(@night)\n destroy(@sky)\n destroy(@sun)\n destroy(", "end": 15629, "score": 0.9981626272201538, "start": 15623, "tag": "USERNAME", "value": "@night" }, { "context": " destroy(@tree3)\n destroy(@night)\n destroy(@sky)\n destroy(@sun)\n destroy(@cloud)\n destro", "end": 15647, "score": 0.9977429509162903, "start": 15643, "tag": "USERNAME", "value": "@sky" }, { "context": "\n destroy(@night)\n destroy(@sky)\n destroy(@sun)\n destroy(@cloud)\n destroy(@grass1)\n des", "end": 15665, "score": 0.9978580474853516, "start": 15661, "tag": "USERNAME", "value": "@sun" }, { "context": "t)\n destroy(@sky)\n destroy(@sun)\n destroy(@cloud)\n destroy(@grass1)\n destroy(@grass2)\n de", "end": 15685, "score": 0.9969482421875, "start": 15679, "tag": "USERNAME", "value": "@cloud" }, { "context": "\n destroy(@sun)\n destroy(@cloud)\n destroy(@grass1)\n destroy(@grass2)\n destroy(@runner)\n de", "end": 15706, "score": 0.9974709749221802, "start": 15699, "tag": "USERNAME", "value": "@grass1" }, { "context": " destroy(@cloud)\n destroy(@grass1)\n destroy(@grass2)\n destroy(@runner)\n destroy(@collect_group)", "end": 15727, "score": 0.9972449541091919, "start": 15720, "tag": "USERNAME", "value": "@grass2" }, { "context": " destroy(@grass1)\n destroy(@grass2)\n destroy(@runner)\n destroy(@collect_group)\n destroy(@player_", "end": 15748, "score": 0.9947507977485657, "start": 15741, "tag": "USERNAME", "value": "@runner" }, { "context": " destroy(@grass2)\n destroy(@runner)\n destroy(@collect_group)\n destroy(@player_group)\n destroy(@avatar_g", "end": 15776, "score": 0.9523786306381226, "start": 15762, "tag": "USERNAME", "value": "@collect_group" }, { "context": "y(@runner)\n destroy(@collect_group)\n destroy(@player_group)\n destroy(@avatar_group)\n destroy(@label_gr", "end": 15803, "score": 0.9553385972976685, "start": 15790, "tag": "USERNAME", "value": "@player_group" }, { "context": "lect_group)\n destroy(@player_group)\n destroy(@avatar_group)\n destroy(@label_group)\n destroy(@players)\n", "end": 15830, "score": 0.9588890075683594, "start": 15817, "tag": "USERNAME", "value": "@avatar_group" }, { "context": "ayer_group)\n destroy(@avatar_group)\n destroy(@label_group)\n destroy(@players)\n\n done:=>\n @game.state", "end": 15856, "score": 0.9666128158569336, "start": 15844, "tag": "USERNAME", "value": "@label_group" }, { "context": "vatar_group)\n destroy(@label_group)\n destroy(@players)\n\n done:=>\n @game.state.start('splash')\n\nLagg", "end": 15878, "score": 0.948302686214447, "start": 15870, "tag": "USERNAME", "value": "@players" } ]
src/Landscape.coffee
jasonhutchens/laggy_dash
1
LaggyDash = window.LaggyDash class Landscape extends Phaser.State SPEED = 1 constructor:-> preload:-> window.laggydash.send({ action: 'spawn' }) create:-> @game.stage.backgroundColor = '#000055' @night = @game.add.sprite(@game.world.centerX, @game.world.centerY, 'night') @night.body = null @night.alpha = 0 @night.anchor.setTo(0.5, 0.5) fade = @game.add.tween(@night) fade.to({ alpha: 1 }, 300000 / SPEED, Phaser.Easing.Linear.None, true, 150000 / SPEED, 999, true) @sky = @game.add.sprite(@game.world.centerX, @game.world.centerY, 'sky') @sky.body = null @sky.alpha = 1 @sky.anchor.setTo(0.5, 0.5) fade = @game.add.tween(@sky) fade.to({ alpha: 0 }, 450000 / SPEED, Phaser.Easing.Linear.None, true, 0, 999, true) @sun = @game.add.sprite(0, 0, 'sun') @sun.body = null @sun.anchor.setTo(0.5, 0.5) @sun.scale.setTo(0.3, 0.4) @sun.x = @game.world.centerX @sun.y = @game.world.centerY * 0.5 - 100 grow = @game.add.tween(@sun.scale) grow.to({ x: 1.5, y: 1.5 }, 450000 / SPEED, Phaser.Easing.Cubic.InOut, true, 0, 999, true) set = @game.add.tween(@sun) set.to({ y: 675 }, 450000 / SPEED, Phaser.Easing.Sinusoidal.InOut, true, 0, 999, true) fade = @game.add.tween(@sun) fade.to({ alpha: 0 }, 450000 / SPEED, Phaser.Easing.Linear.None, true, 0, true, true) @cloud = @game.add.sprite(1000, 70, 'cloud') @cloud.body = null @cloud.alpha = 0.4 move = @game.add.tween(@cloud) move.to({x: -800}, 70000 / SPEED, Phaser.Easing.Linear.None, true, 0, 999) @mountain0a = @game.add.sprite(0, 180, 'mountain0') @mountain0a.body = null @mountain0b = @game.add.sprite(2000, 180, 'mountain0') @mountain0b.body = null @collect_group = @game.add.group() @mountain1a = @game.add.sprite(0, 180, 'mountain1') @mountain1a.body = null @mountain1b = @game.add.sprite(2000, 180, 'mountain1') @mountain1b.body = null @player_group = @game.add.group() @heightmap = [] y = 122 for x in [0..@mountain1a.width] solid = @mountain1a.input.checkPixel(x, y) if solid while solid y -= 1 solid = @mountain1a.input.checkPixel(x, y) y += 1 else until solid y += 1 solid = @mountain1a.input.checkPixel(x, y) break if y > 200 @heightmap.push(y) @mountain2a = @game.add.sprite(0, 180, 'mountain2') @mountain2a.body = null @mountain2b = @game.add.sprite(2000, 180, 'mountain2') @mountain2b.body = null @mountain3a = @game.add.sprite(0, 180, 'mountain3') @mountain3a.body = null @mountain3a.alpha = 0.4 @mountain3b = @game.add.sprite(2000, 180, 'mountain3') @mountain3b.body = null @mountain3b.alpha = 0.4 move = @game.add.tween(@mountain0a) move.to({x: -2000}, 31000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain0b) move.to({x: 0}, 31000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain1a) move.to({x: -2000}, 18000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain1b) move.to({x: 0}, 18000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain2a) move.to({x: -2000}, 13000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain2b) move.to({x: 0}, 13000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain3a) move.to({x: -2000}, 7000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain3b) move.to({x: 0}, 7000, Phaser.Easing.Linear.None, true, 0, 999) @avatar_group = @game.add.group() @tree0 = @game.add.sprite(2000, 490, 'tree0') @tree0.body = null @tree0.anchor.setTo(0.5, 1) move = @game.add.tween(@tree0) move.to({x: -2000}, 3400 / SPEED, Phaser.Easing.Linear.None, true, 3000 / SPEED, 999) @tree1 = @game.add.sprite(2000, 490, 'tree1') @tree1.body = null @tree1.anchor.setTo(0.5, 1) move = @game.add.tween(@tree1) move.to({x: -2000}, 3500 / SPEED, Phaser.Easing.Linear.None, true, 7000 / SPEED, 999) @tree2 = @game.add.sprite(2000, 490, 'tree2') @tree2.body = null @tree2.anchor.setTo(0.5, 1) move = @game.add.tween(@tree2) move.to({x: -2000}, 3600 / SPEED, Phaser.Easing.Linear.None, true, 13000 / SPEED, 999) @tree3 = @game.add.sprite(2000, 490, 'tree3') @tree3.body = null @tree3.anchor.setTo(0.5, 1) move = @game.add.tween(@tree3) move.to({x: -2000}, 3400 / SPEED, Phaser.Easing.Linear.None, true, 17000 / SPEED, 999) @grass1 = @game.add.sprite(0, 380, 'grass') @grass1.body = null @grass2 = @game.add.sprite(896, 380, 'grass') @grass2.body = null move = @game.add.tween(@grass1) move.to({x: -896}, 1000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@grass2) move.to({x: 0}, 1000, Phaser.Easing.Linear.None, true, 0, 999) @label_group = @game.add.group() @restart = false @score = 0 @position = 0 @players = {} @hero = null @addPlayer(window.laggydash.user.replace(/:.*$/, ''), @game.player_name, true) window.laggydash.loadAvatar(@game.player_name) key = @game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR) key.onDown.add(@jump) @game.input.onTap.add(@jump) @current = null @timer = @game.time.create() @timer.start() update:-> @position += 1 min = Math.round(Math.min(@mountain1a.x, @mountain1b.x)) if @position > 200 && @position % 50 == 0 @addCollect(min) @player_group.forEachAlive (player) => @updatePlayer(player, min) if @restart @game.state.start('splash') else @updateAvatar(@hero) if @current? @updateAvatar(@players[@current]) if @prev? @updateAvatar(@players[@prev]) updateAvatar:(player)-> return unless player? && player.avatar? player.avatar.x = player.runner.x player.runner.dot.x = player.runner.x player.label.x = player.runner.x - player.label.width / 2 player.runner.dot.y = player.avatar.y - player.avatar.height - 5 player.runner.dot.height = player.runner.dot.y - player.runner.y - 8 addCollect:(min)-> obj = if @position % 100 == 0 && @game.rnd.frac() < 0.4 || @game.rnd.frac() < 0.1 @game.add.sprite(900, 0, 'bomb') else @game.add.sprite(900, 0, 'coin') obj.body.allowGravity = false w = if obj.key == 'bomb' then 5 else 15 h = w obj.body.setRectangle(w,h,obj.width/2-w/2-1,obj.height/2-h/2) obj.body.x = obj.x obj.anchor.setTo(0.5, 0.5) obj.animations.add('spin', [0, 1, 2, 3, 4, 5], 10, true) obj.animations.play('spin') @collect_group.add(obj) x = (obj.x - min) % 2000 h = @game.rnd.pick([20, 80]) obj.y = @heightmap[Math.round(x)] + @mountain1a.y - h obj.alpha = 1 obj.move = @game.add.tween(obj) obj.move.to({x: 350}, 5000, Phaser.Easing.Linear.None, true, 0) obj.move.onComplete.add => obj.kill() obj.fade = @game.add.tween(obj) obj.fade.to({ alpha: 0.0 }, 2000, Phaser.Easing.Linear.None, true, 2500) obj.revive() if @game.rnd.frac() < 0.25 obj.jump = @game.add.tween(obj) d = if h == 80 then 60 else -60 obj.jump.to({y: obj.y + d}, 300, Phaser.Easing.Linear.None, true, 1400) updatePlayer:(player, min)-> return if player.bang x = (player.x - min) % 2000 y = @heightmap[Math.round(x)] + @mountain1a.y wasOnGround = player.onGround delta = player.y - y player.onGround = delta > 0 player.jump = false if delta < -20 if player.onGround player.y = y player.body.velocity.y = 0 if player.jump player.jump = false player.onGround = false player.y -= 10 player.body.velocity.y = -200 player.animations.stop() player.frame = if player.key == 'runner' then 4 else 2 if !wasOnGround && player.onGround player.play('run') if player.key == 'wolf' && player.x == player.target && player.onGround player.target = @game.rnd.integerInRange(100, 500) move = @game.add.tween(player) move.to({x: player.target}, @game.rnd.realInRange(3000, 8000), Phaser.Easing.Sinusoidal.InOut, true, @game.rnd.realInRange(0, 10000)) if player.key == 'runner' @game.physics.overlap(player, @collect_group, @hit) jump:=> @player_group.forEachAlive (player) => if player.key == 'runner' player.jump = true window.laggydash.send({ action: 'jump' }) gameOver:=> message = "You died. Score: #{@score}." options = labels: ok: "Tweet It" cancel: "Play Again" alertify.set(options) alertify.confirm message, (event, input) => @restart = true if event names = ("@#{player.avatar.name}" for id, player of @players) names = _.uniq(names) chasers = switch names.length when 0 "nobody at all" when 1 names[0] when 2 "#{names[0]} and #{names[1]}" else "#{names[0]}, #{names[1]} and others" message = switch @score when 0 "I ate a bomb after collecting nothing while being chased by #{chasers}!" when 1 "I ate a bomb after collecting one measly coin while being chased by #{chasers}!" else "I ate a bomb after collecting #{@score} coins while being chased by #{chasers}!" window.laggydash.tweet(message, names) bang:(player, x, y)=> player.runner.body.velocity.y = -150 player.runner.body.velocity.x = -150 player.runner.animations.stop() player.runner.frame = 3 explosion = @game.add.sprite(x, y, 'explosion') explosion.body = null explosion.anchor.setTo(0.5, 0.5) explosion.animations.add('bang', [0, 1, 2, 3], 6, false) explosion.animations.play('bang', 6, false, true) move = @game.add.tween(explosion) move.to({x: explosion.x - 550}, 5000, Phaser.Easing.Linear.None, true, 0) flash = @game.add.tween(player.runner) flash.to({ alpha: 0.0 }, 100, Phaser.Easing.Sinusoidal.InOut, true, 0, 10, true) fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) fade = @game.add.tween(player.label) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) player.runner.bang = true hit:(runner, obj)=> @collect(obj) collect:(obj)-> if obj.key == 'coin' @score += 1 else timer = @game.time.create() timer.add(1000, @gameOver) timer.start() @bang(@hero, obj.x, obj.y) window.laggydash.send({ action: 'bang' }) @game.tweens.remove(obj.move) obj.move = null @game.tweens.remove(obj.jump) obj.jump = null @game.tweens.remove(obj.fade) obj.fade = null obj.kill() addPlayer:(id, name, isPlayer=false)-> x = if isPlayer then 600 else @game.rnd.integerInRange(100, 500) s = if isPlayer then 'runner' else 'wolf' f = if isPlayer then 8 else 12 o = if isPlayer then 0.9 else 1.0 runner = @game.add.sprite(x, 0, s) runner.animations.add('run', [0, 1, 2, 3, 4, 5], f, true) runner.anchor.setTo(0.5, o) runner.onGround = false runner.jump = false runner.bang = false runner.frame = if isPlayer then 3 else 4 runner.target = x runner.id = id if isPlayer w = 20 h = 40 runner.body.setRectangle(w,h,runner.width/2-w/2,runner.height/2-h/2) runner.body.x = runner.x @player_group.add(runner) avatar = @game.add.sprite(x, 475, "@#{name}") avatar.body = null avatar.id = id avatar.name = name avatar.width = 60 avatar.height = 60 avatar.anchor.setTo(0.5, 1.0) avatar.alpha = 0.0 avatar.inputEnabled = true avatar.useHandCursor = true avatar.events.onInputDown.add => if avatar.alpha > 0.5 window.laggydash.showUser(name) @avatar_group.add(avatar) dot = @game.add.sprite(x, avatar.y, "dot") dot.body = null dot.id = id dot.height = 100 dot.anchor.setTo(0.5, 1.0) dot.alpha = 0.0 runner.dot = dot runner.avatar = avatar @avatar_group.add(dot) style = font: "10pt Courier" fill: "#ffffff" label = @game.add.text(x, 480, "@#{name}", style) label.x -= label.width / 2 label.alpha = 0.0 @label_group.add(label) if isPlayer fade = @game.add.tween(avatar) fade.to({ alpha: 0.8 }, 1000, Phaser.Easing.Linear.None, true, 2000) fade = @game.add.tween(dot) fade.to({ alpha: 0.3 }, 1000, Phaser.Easing.Linear.None, true, 2000) fade = @game.add.tween(label) fade.to({ alpha: 1.0 }, 1000, Phaser.Easing.Linear.None, true, 2000) @hero = runner: runner avatar: avatar label: label else @players[id] = runner: runner avatar: avatar label: label showPlayer:=> ids = _.keys(@players) if ids.length == 0 @current = null @prev = null return if @current? && ids.length > 1 @prev = @current ids = _.without(ids, @current) player = @players[@current] fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) fade = @game.add.tween(player.label) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) @current = @game.rnd.pick(ids) player = @players[@current] fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.8 }, 1000, Phaser.Easing.Linear.None, true, 500) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.3 }, 1000, Phaser.Easing.Linear.None, true, 500) fade = @game.add.tween(player.label) fade.to({ alpha: 1.0 }, 1000, Phaser.Easing.Linear.None, true, 500) @timer.remove(event) for event in @timer.events @timer.add(8000, @showPlayer) avatarLoaded:(key)-> @avatar_group.forEach (avatar)=> if avatar.key == "__missing" && key == "@#{avatar.name}" avatar.loadTexture(key) avatar.width = 60 avatar.height = 60 handle:(remote)-> switch remote.action when 'spawn' unless @players[remote.id]? @spawn(remote.id, remote.name) when 'bail' @delPlayer(remote.id) when 'jump' unless @players[remote.id]? @spawn(remote.id, remote.name) @jmpPlayer(remote.id) when 'bang' @diePlayer(remote.id) spawn:(id, name)-> @addPlayer(id, name) @showPlayer() if @current == null delPlayer:(id)-> return unless @players[id]? @players[id].runner.dot.kill() @players[id].runner.kill() @players[id].avatar.kill() @players[id].label.kill() @remPlayer(id) diePlayer:(id)-> return unless @players[id]? player = @players[id].runner @bang(@players[id], player.x, player.y) @remPlayer(id) remPlayer:(id)-> return unless @players[id]? delete(@players[id]) if @current == id @current = null @showPlayer() @prev = null if @prev == id jmpPlayer:(id)-> return unless @players[id]? player = @players[id].runner player.jump = true destroy:-> destroy(@tree0) destroy(@tree1) destroy(@tree2) destroy(@tree3) destroy(@night) destroy(@sky) destroy(@sun) destroy(@cloud) destroy(@grass1) destroy(@grass2) destroy(@runner) destroy(@collect_group) destroy(@player_group) destroy(@avatar_group) destroy(@label_group) destroy(@players) done:=> @game.state.start('splash') LaggyDash.Landscape = Landscape
8747
LaggyDash = window.LaggyDash class Landscape extends Phaser.State SPEED = 1 constructor:-> preload:-> window.laggydash.send({ action: 'spawn' }) create:-> @game.stage.backgroundColor = '#000055' @night = @game.add.sprite(@game.world.centerX, @game.world.centerY, 'night') @night.body = null @night.alpha = 0 @night.anchor.setTo(0.5, 0.5) fade = @game.add.tween(@night) fade.to({ alpha: 1 }, 300000 / SPEED, Phaser.Easing.Linear.None, true, 150000 / SPEED, 999, true) @sky = @game.add.sprite(@game.world.centerX, @game.world.centerY, 'sky') @sky.body = null @sky.alpha = 1 @sky.anchor.setTo(0.5, 0.5) fade = @game.add.tween(@sky) fade.to({ alpha: 0 }, 450000 / SPEED, Phaser.Easing.Linear.None, true, 0, 999, true) @sun = @game.add.sprite(0, 0, 'sun') @sun.body = null @sun.anchor.setTo(0.5, 0.5) @sun.scale.setTo(0.3, 0.4) @sun.x = @game.world.centerX @sun.y = @game.world.centerY * 0.5 - 100 grow = @game.add.tween(@sun.scale) grow.to({ x: 1.5, y: 1.5 }, 450000 / SPEED, Phaser.Easing.Cubic.InOut, true, 0, 999, true) set = @game.add.tween(@sun) set.to({ y: 675 }, 450000 / SPEED, Phaser.Easing.Sinusoidal.InOut, true, 0, 999, true) fade = @game.add.tween(@sun) fade.to({ alpha: 0 }, 450000 / SPEED, Phaser.Easing.Linear.None, true, 0, true, true) @cloud = @game.add.sprite(1000, 70, 'cloud') @cloud.body = null @cloud.alpha = 0.4 move = @game.add.tween(@cloud) move.to({x: -800}, 70000 / SPEED, Phaser.Easing.Linear.None, true, 0, 999) @mountain0a = @game.add.sprite(0, 180, 'mountain0') @mountain0a.body = null @mountain0b = @game.add.sprite(2000, 180, 'mountain0') @mountain0b.body = null @collect_group = @game.add.group() @mountain1a = @game.add.sprite(0, 180, 'mountain1') @mountain1a.body = null @mountain1b = @game.add.sprite(2000, 180, 'mountain1') @mountain1b.body = null @player_group = @game.add.group() @heightmap = [] y = 122 for x in [0..@mountain1a.width] solid = @mountain1a.input.checkPixel(x, y) if solid while solid y -= 1 solid = @mountain1a.input.checkPixel(x, y) y += 1 else until solid y += 1 solid = @mountain1a.input.checkPixel(x, y) break if y > 200 @heightmap.push(y) @mountain2a = @game.add.sprite(0, 180, 'mountain2') @mountain2a.body = null @mountain2b = @game.add.sprite(2000, 180, 'mountain2') @mountain2b.body = null @mountain3a = @game.add.sprite(0, 180, 'mountain3') @mountain3a.body = null @mountain3a.alpha = 0.4 @mountain3b = @game.add.sprite(2000, 180, 'mountain3') @mountain3b.body = null @mountain3b.alpha = 0.4 move = @game.add.tween(@mountain0a) move.to({x: -2000}, 31000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain0b) move.to({x: 0}, 31000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain1a) move.to({x: -2000}, 18000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain1b) move.to({x: 0}, 18000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain2a) move.to({x: -2000}, 13000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain2b) move.to({x: 0}, 13000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain3a) move.to({x: -2000}, 7000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain3b) move.to({x: 0}, 7000, Phaser.Easing.Linear.None, true, 0, 999) @avatar_group = @game.add.group() @tree0 = @game.add.sprite(2000, 490, 'tree0') @tree0.body = null @tree0.anchor.setTo(0.5, 1) move = @game.add.tween(@tree0) move.to({x: -2000}, 3400 / SPEED, Phaser.Easing.Linear.None, true, 3000 / SPEED, 999) @tree1 = @game.add.sprite(2000, 490, 'tree1') @tree1.body = null @tree1.anchor.setTo(0.5, 1) move = @game.add.tween(@tree1) move.to({x: -2000}, 3500 / SPEED, Phaser.Easing.Linear.None, true, 7000 / SPEED, 999) @tree2 = @game.add.sprite(2000, 490, 'tree2') @tree2.body = null @tree2.anchor.setTo(0.5, 1) move = @game.add.tween(@tree2) move.to({x: -2000}, 3600 / SPEED, Phaser.Easing.Linear.None, true, 13000 / SPEED, 999) @tree3 = @game.add.sprite(2000, 490, 'tree3') @tree3.body = null @tree3.anchor.setTo(0.5, 1) move = @game.add.tween(@tree3) move.to({x: -2000}, 3400 / SPEED, Phaser.Easing.Linear.None, true, 17000 / SPEED, 999) @grass1 = @game.add.sprite(0, 380, 'grass') @grass1.body = null @grass2 = @game.add.sprite(896, 380, 'grass') @grass2.body = null move = @game.add.tween(@grass1) move.to({x: -896}, 1000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@grass2) move.to({x: 0}, 1000, Phaser.Easing.Linear.None, true, 0, 999) @label_group = @game.add.group() @restart = false @score = 0 @position = 0 @players = {} @hero = null @addPlayer(window.laggydash.user.replace(/:.*$/, ''), @game.player_name, true) window.laggydash.loadAvatar(@game.player_name) key = @game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR) key.onDown.add(@jump) @game.input.onTap.add(@jump) @current = null @timer = @game.time.create() @timer.start() update:-> @position += 1 min = Math.round(Math.min(@mountain1a.x, @mountain1b.x)) if @position > 200 && @position % 50 == 0 @addCollect(min) @player_group.forEachAlive (player) => @updatePlayer(player, min) if @restart @game.state.start('splash') else @updateAvatar(@hero) if @current? @updateAvatar(@players[@current]) if @prev? @updateAvatar(@players[@prev]) updateAvatar:(player)-> return unless player? && player.avatar? player.avatar.x = player.runner.x player.runner.dot.x = player.runner.x player.label.x = player.runner.x - player.label.width / 2 player.runner.dot.y = player.avatar.y - player.avatar.height - 5 player.runner.dot.height = player.runner.dot.y - player.runner.y - 8 addCollect:(min)-> obj = if @position % 100 == 0 && @game.rnd.frac() < 0.4 || @game.rnd.frac() < 0.1 @game.add.sprite(900, 0, 'bomb') else @game.add.sprite(900, 0, 'coin') obj.body.allowGravity = false w = if obj.key == '<KEY>' then 5 else 15 h = w obj.body.setRectangle(w,h,obj.width/2-w/2-1,obj.height/2-h/2) obj.body.x = obj.x obj.anchor.setTo(0.5, 0.5) obj.animations.add('spin', [0, 1, 2, 3, 4, 5], 10, true) obj.animations.play('spin') @collect_group.add(obj) x = (obj.x - min) % 2000 h = @game.rnd.pick([20, 80]) obj.y = @heightmap[Math.round(x)] + @mountain1a.y - h obj.alpha = 1 obj.move = @game.add.tween(obj) obj.move.to({x: 350}, 5000, Phaser.Easing.Linear.None, true, 0) obj.move.onComplete.add => obj.kill() obj.fade = @game.add.tween(obj) obj.fade.to({ alpha: 0.0 }, 2000, Phaser.Easing.Linear.None, true, 2500) obj.revive() if @game.rnd.frac() < 0.25 obj.jump = @game.add.tween(obj) d = if h == 80 then 60 else -60 obj.jump.to({y: obj.y + d}, 300, Phaser.Easing.Linear.None, true, 1400) updatePlayer:(player, min)-> return if player.bang x = (player.x - min) % 2000 y = @heightmap[Math.round(x)] + @mountain1a.y wasOnGround = player.onGround delta = player.y - y player.onGround = delta > 0 player.jump = false if delta < -20 if player.onGround player.y = y player.body.velocity.y = 0 if player.jump player.jump = false player.onGround = false player.y -= 10 player.body.velocity.y = -200 player.animations.stop() player.frame = if player.key == '<KEY>' then 4 else 2 if !wasOnGround && player.onGround player.play('run') if player.key == '<KEY>' && player.x == player.target && player.onGround player.target = @game.rnd.integerInRange(100, 500) move = @game.add.tween(player) move.to({x: player.target}, @game.rnd.realInRange(3000, 8000), Phaser.Easing.Sinusoidal.InOut, true, @game.rnd.realInRange(0, 10000)) if player.key == '<KEY>' @game.physics.overlap(player, @collect_group, @hit) jump:=> @player_group.forEachAlive (player) => if player.key == '<KEY>' player.jump = true window.laggydash.send({ action: 'jump' }) gameOver:=> message = "You died. Score: #{@score}." options = labels: ok: "Tweet It" cancel: "Play Again" alertify.set(options) alertify.confirm message, (event, input) => @restart = true if event names = ("@#{player.avatar.name}" for id, player of @players) names = _.uniq(names) chasers = switch names.length when 0 "nobody at all" when 1 names[0] when 2 "#{names[0]} and #{names[1]}" else "#{names[0]}, #{names[1]} and others" message = switch @score when 0 "I ate a bomb after collecting nothing while being chased by #{chasers}!" when 1 "I ate a bomb after collecting one measly coin while being chased by #{chasers}!" else "I ate a bomb after collecting #{@score} coins while being chased by #{chasers}!" window.laggydash.tweet(message, names) bang:(player, x, y)=> player.runner.body.velocity.y = -150 player.runner.body.velocity.x = -150 player.runner.animations.stop() player.runner.frame = 3 explosion = @game.add.sprite(x, y, 'explosion') explosion.body = null explosion.anchor.setTo(0.5, 0.5) explosion.animations.add('bang', [0, 1, 2, 3], 6, false) explosion.animations.play('bang', 6, false, true) move = @game.add.tween(explosion) move.to({x: explosion.x - 550}, 5000, Phaser.Easing.Linear.None, true, 0) flash = @game.add.tween(player.runner) flash.to({ alpha: 0.0 }, 100, Phaser.Easing.Sinusoidal.InOut, true, 0, 10, true) fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) fade = @game.add.tween(player.label) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) player.runner.bang = true hit:(runner, obj)=> @collect(obj) collect:(obj)-> if obj.key == 'coin' @score += 1 else timer = @game.time.create() timer.add(1000, @gameOver) timer.start() @bang(@hero, obj.x, obj.y) window.laggydash.send({ action: 'bang' }) @game.tweens.remove(obj.move) obj.move = null @game.tweens.remove(obj.jump) obj.jump = null @game.tweens.remove(obj.fade) obj.fade = null obj.kill() addPlayer:(id, name, isPlayer=false)-> x = if isPlayer then 600 else @game.rnd.integerInRange(100, 500) s = if isPlayer then 'runner' else 'wolf' f = if isPlayer then 8 else 12 o = if isPlayer then 0.9 else 1.0 runner = @game.add.sprite(x, 0, s) runner.animations.add('run', [0, 1, 2, 3, 4, 5], f, true) runner.anchor.setTo(0.5, o) runner.onGround = false runner.jump = false runner.bang = false runner.frame = if isPlayer then 3 else 4 runner.target = x runner.id = id if isPlayer w = 20 h = 40 runner.body.setRectangle(w,h,runner.width/2-w/2,runner.height/2-h/2) runner.body.x = runner.x @player_group.add(runner) avatar = @game.add.sprite(x, 475, "@#{name}") avatar.body = null avatar.id = id avatar.name = <NAME> avatar.width = 60 avatar.height = 60 avatar.anchor.setTo(0.5, 1.0) avatar.alpha = 0.0 avatar.inputEnabled = true avatar.useHandCursor = true avatar.events.onInputDown.add => if avatar.alpha > 0.5 window.laggydash.showUser(name) @avatar_group.add(avatar) dot = @game.add.sprite(x, avatar.y, "dot") dot.body = null dot.id = id dot.height = 100 dot.anchor.setTo(0.5, 1.0) dot.alpha = 0.0 runner.dot = dot runner.avatar = avatar @avatar_group.add(dot) style = font: "10pt Courier" fill: "#ffffff" label = @game.add.text(x, 480, "@#{name}", style) label.x -= label.width / 2 label.alpha = 0.0 @label_group.add(label) if isPlayer fade = @game.add.tween(avatar) fade.to({ alpha: 0.8 }, 1000, Phaser.Easing.Linear.None, true, 2000) fade = @game.add.tween(dot) fade.to({ alpha: 0.3 }, 1000, Phaser.Easing.Linear.None, true, 2000) fade = @game.add.tween(label) fade.to({ alpha: 1.0 }, 1000, Phaser.Easing.Linear.None, true, 2000) @hero = runner: runner avatar: avatar label: label else @players[id] = runner: runner avatar: avatar label: label showPlayer:=> ids = _.keys(@players) if ids.length == 0 @current = null @prev = null return if @current? && ids.length > 1 @prev = @current ids = _.without(ids, @current) player = @players[@current] fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) fade = @game.add.tween(player.label) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) @current = @game.rnd.pick(ids) player = @players[@current] fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.8 }, 1000, Phaser.Easing.Linear.None, true, 500) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.3 }, 1000, Phaser.Easing.Linear.None, true, 500) fade = @game.add.tween(player.label) fade.to({ alpha: 1.0 }, 1000, Phaser.Easing.Linear.None, true, 500) @timer.remove(event) for event in @timer.events @timer.add(8000, @showPlayer) avatarLoaded:(key)-> @avatar_group.forEach (avatar)=> if avatar.key == "__missing" && key == "@#{avatar.name}" avatar.loadTexture(key) avatar.width = 60 avatar.height = 60 handle:(remote)-> switch remote.action when 'spawn' unless @players[remote.id]? @spawn(remote.id, remote.name) when 'bail' @delPlayer(remote.id) when 'jump' unless @players[remote.id]? @spawn(remote.id, remote.name) @jmpPlayer(remote.id) when 'bang' @diePlayer(remote.id) spawn:(id, name)-> @addPlayer(id, name) @showPlayer() if @current == null delPlayer:(id)-> return unless @players[id]? @players[id].runner.dot.kill() @players[id].runner.kill() @players[id].avatar.kill() @players[id].label.kill() @remPlayer(id) diePlayer:(id)-> return unless @players[id]? player = @players[id].runner @bang(@players[id], player.x, player.y) @remPlayer(id) remPlayer:(id)-> return unless @players[id]? delete(@players[id]) if @current == id @current = null @showPlayer() @prev = null if @prev == id jmpPlayer:(id)-> return unless @players[id]? player = @players[id].runner player.jump = true destroy:-> destroy(@tree0) destroy(@tree1) destroy(@tree2) destroy(@tree3) destroy(@night) destroy(@sky) destroy(@sun) destroy(@cloud) destroy(@grass1) destroy(@grass2) destroy(@runner) destroy(@collect_group) destroy(@player_group) destroy(@avatar_group) destroy(@label_group) destroy(@players) done:=> @game.state.start('splash') LaggyDash.Landscape = Landscape
true
LaggyDash = window.LaggyDash class Landscape extends Phaser.State SPEED = 1 constructor:-> preload:-> window.laggydash.send({ action: 'spawn' }) create:-> @game.stage.backgroundColor = '#000055' @night = @game.add.sprite(@game.world.centerX, @game.world.centerY, 'night') @night.body = null @night.alpha = 0 @night.anchor.setTo(0.5, 0.5) fade = @game.add.tween(@night) fade.to({ alpha: 1 }, 300000 / SPEED, Phaser.Easing.Linear.None, true, 150000 / SPEED, 999, true) @sky = @game.add.sprite(@game.world.centerX, @game.world.centerY, 'sky') @sky.body = null @sky.alpha = 1 @sky.anchor.setTo(0.5, 0.5) fade = @game.add.tween(@sky) fade.to({ alpha: 0 }, 450000 / SPEED, Phaser.Easing.Linear.None, true, 0, 999, true) @sun = @game.add.sprite(0, 0, 'sun') @sun.body = null @sun.anchor.setTo(0.5, 0.5) @sun.scale.setTo(0.3, 0.4) @sun.x = @game.world.centerX @sun.y = @game.world.centerY * 0.5 - 100 grow = @game.add.tween(@sun.scale) grow.to({ x: 1.5, y: 1.5 }, 450000 / SPEED, Phaser.Easing.Cubic.InOut, true, 0, 999, true) set = @game.add.tween(@sun) set.to({ y: 675 }, 450000 / SPEED, Phaser.Easing.Sinusoidal.InOut, true, 0, 999, true) fade = @game.add.tween(@sun) fade.to({ alpha: 0 }, 450000 / SPEED, Phaser.Easing.Linear.None, true, 0, true, true) @cloud = @game.add.sprite(1000, 70, 'cloud') @cloud.body = null @cloud.alpha = 0.4 move = @game.add.tween(@cloud) move.to({x: -800}, 70000 / SPEED, Phaser.Easing.Linear.None, true, 0, 999) @mountain0a = @game.add.sprite(0, 180, 'mountain0') @mountain0a.body = null @mountain0b = @game.add.sprite(2000, 180, 'mountain0') @mountain0b.body = null @collect_group = @game.add.group() @mountain1a = @game.add.sprite(0, 180, 'mountain1') @mountain1a.body = null @mountain1b = @game.add.sprite(2000, 180, 'mountain1') @mountain1b.body = null @player_group = @game.add.group() @heightmap = [] y = 122 for x in [0..@mountain1a.width] solid = @mountain1a.input.checkPixel(x, y) if solid while solid y -= 1 solid = @mountain1a.input.checkPixel(x, y) y += 1 else until solid y += 1 solid = @mountain1a.input.checkPixel(x, y) break if y > 200 @heightmap.push(y) @mountain2a = @game.add.sprite(0, 180, 'mountain2') @mountain2a.body = null @mountain2b = @game.add.sprite(2000, 180, 'mountain2') @mountain2b.body = null @mountain3a = @game.add.sprite(0, 180, 'mountain3') @mountain3a.body = null @mountain3a.alpha = 0.4 @mountain3b = @game.add.sprite(2000, 180, 'mountain3') @mountain3b.body = null @mountain3b.alpha = 0.4 move = @game.add.tween(@mountain0a) move.to({x: -2000}, 31000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain0b) move.to({x: 0}, 31000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain1a) move.to({x: -2000}, 18000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain1b) move.to({x: 0}, 18000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain2a) move.to({x: -2000}, 13000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain2b) move.to({x: 0}, 13000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain3a) move.to({x: -2000}, 7000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@mountain3b) move.to({x: 0}, 7000, Phaser.Easing.Linear.None, true, 0, 999) @avatar_group = @game.add.group() @tree0 = @game.add.sprite(2000, 490, 'tree0') @tree0.body = null @tree0.anchor.setTo(0.5, 1) move = @game.add.tween(@tree0) move.to({x: -2000}, 3400 / SPEED, Phaser.Easing.Linear.None, true, 3000 / SPEED, 999) @tree1 = @game.add.sprite(2000, 490, 'tree1') @tree1.body = null @tree1.anchor.setTo(0.5, 1) move = @game.add.tween(@tree1) move.to({x: -2000}, 3500 / SPEED, Phaser.Easing.Linear.None, true, 7000 / SPEED, 999) @tree2 = @game.add.sprite(2000, 490, 'tree2') @tree2.body = null @tree2.anchor.setTo(0.5, 1) move = @game.add.tween(@tree2) move.to({x: -2000}, 3600 / SPEED, Phaser.Easing.Linear.None, true, 13000 / SPEED, 999) @tree3 = @game.add.sprite(2000, 490, 'tree3') @tree3.body = null @tree3.anchor.setTo(0.5, 1) move = @game.add.tween(@tree3) move.to({x: -2000}, 3400 / SPEED, Phaser.Easing.Linear.None, true, 17000 / SPEED, 999) @grass1 = @game.add.sprite(0, 380, 'grass') @grass1.body = null @grass2 = @game.add.sprite(896, 380, 'grass') @grass2.body = null move = @game.add.tween(@grass1) move.to({x: -896}, 1000, Phaser.Easing.Linear.None, true, 0, 999) move = @game.add.tween(@grass2) move.to({x: 0}, 1000, Phaser.Easing.Linear.None, true, 0, 999) @label_group = @game.add.group() @restart = false @score = 0 @position = 0 @players = {} @hero = null @addPlayer(window.laggydash.user.replace(/:.*$/, ''), @game.player_name, true) window.laggydash.loadAvatar(@game.player_name) key = @game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR) key.onDown.add(@jump) @game.input.onTap.add(@jump) @current = null @timer = @game.time.create() @timer.start() update:-> @position += 1 min = Math.round(Math.min(@mountain1a.x, @mountain1b.x)) if @position > 200 && @position % 50 == 0 @addCollect(min) @player_group.forEachAlive (player) => @updatePlayer(player, min) if @restart @game.state.start('splash') else @updateAvatar(@hero) if @current? @updateAvatar(@players[@current]) if @prev? @updateAvatar(@players[@prev]) updateAvatar:(player)-> return unless player? && player.avatar? player.avatar.x = player.runner.x player.runner.dot.x = player.runner.x player.label.x = player.runner.x - player.label.width / 2 player.runner.dot.y = player.avatar.y - player.avatar.height - 5 player.runner.dot.height = player.runner.dot.y - player.runner.y - 8 addCollect:(min)-> obj = if @position % 100 == 0 && @game.rnd.frac() < 0.4 || @game.rnd.frac() < 0.1 @game.add.sprite(900, 0, 'bomb') else @game.add.sprite(900, 0, 'coin') obj.body.allowGravity = false w = if obj.key == 'PI:KEY:<KEY>END_PI' then 5 else 15 h = w obj.body.setRectangle(w,h,obj.width/2-w/2-1,obj.height/2-h/2) obj.body.x = obj.x obj.anchor.setTo(0.5, 0.5) obj.animations.add('spin', [0, 1, 2, 3, 4, 5], 10, true) obj.animations.play('spin') @collect_group.add(obj) x = (obj.x - min) % 2000 h = @game.rnd.pick([20, 80]) obj.y = @heightmap[Math.round(x)] + @mountain1a.y - h obj.alpha = 1 obj.move = @game.add.tween(obj) obj.move.to({x: 350}, 5000, Phaser.Easing.Linear.None, true, 0) obj.move.onComplete.add => obj.kill() obj.fade = @game.add.tween(obj) obj.fade.to({ alpha: 0.0 }, 2000, Phaser.Easing.Linear.None, true, 2500) obj.revive() if @game.rnd.frac() < 0.25 obj.jump = @game.add.tween(obj) d = if h == 80 then 60 else -60 obj.jump.to({y: obj.y + d}, 300, Phaser.Easing.Linear.None, true, 1400) updatePlayer:(player, min)-> return if player.bang x = (player.x - min) % 2000 y = @heightmap[Math.round(x)] + @mountain1a.y wasOnGround = player.onGround delta = player.y - y player.onGround = delta > 0 player.jump = false if delta < -20 if player.onGround player.y = y player.body.velocity.y = 0 if player.jump player.jump = false player.onGround = false player.y -= 10 player.body.velocity.y = -200 player.animations.stop() player.frame = if player.key == 'PI:KEY:<KEY>END_PI' then 4 else 2 if !wasOnGround && player.onGround player.play('run') if player.key == 'PI:KEY:<KEY>END_PI' && player.x == player.target && player.onGround player.target = @game.rnd.integerInRange(100, 500) move = @game.add.tween(player) move.to({x: player.target}, @game.rnd.realInRange(3000, 8000), Phaser.Easing.Sinusoidal.InOut, true, @game.rnd.realInRange(0, 10000)) if player.key == 'PI:KEY:<KEY>END_PI' @game.physics.overlap(player, @collect_group, @hit) jump:=> @player_group.forEachAlive (player) => if player.key == 'PI:KEY:<KEY>END_PI' player.jump = true window.laggydash.send({ action: 'jump' }) gameOver:=> message = "You died. Score: #{@score}." options = labels: ok: "Tweet It" cancel: "Play Again" alertify.set(options) alertify.confirm message, (event, input) => @restart = true if event names = ("@#{player.avatar.name}" for id, player of @players) names = _.uniq(names) chasers = switch names.length when 0 "nobody at all" when 1 names[0] when 2 "#{names[0]} and #{names[1]}" else "#{names[0]}, #{names[1]} and others" message = switch @score when 0 "I ate a bomb after collecting nothing while being chased by #{chasers}!" when 1 "I ate a bomb after collecting one measly coin while being chased by #{chasers}!" else "I ate a bomb after collecting #{@score} coins while being chased by #{chasers}!" window.laggydash.tweet(message, names) bang:(player, x, y)=> player.runner.body.velocity.y = -150 player.runner.body.velocity.x = -150 player.runner.animations.stop() player.runner.frame = 3 explosion = @game.add.sprite(x, y, 'explosion') explosion.body = null explosion.anchor.setTo(0.5, 0.5) explosion.animations.add('bang', [0, 1, 2, 3], 6, false) explosion.animations.play('bang', 6, false, true) move = @game.add.tween(explosion) move.to({x: explosion.x - 550}, 5000, Phaser.Easing.Linear.None, true, 0) flash = @game.add.tween(player.runner) flash.to({ alpha: 0.0 }, 100, Phaser.Easing.Sinusoidal.InOut, true, 0, 10, true) fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) fade = @game.add.tween(player.label) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true, 0) player.runner.bang = true hit:(runner, obj)=> @collect(obj) collect:(obj)-> if obj.key == 'coin' @score += 1 else timer = @game.time.create() timer.add(1000, @gameOver) timer.start() @bang(@hero, obj.x, obj.y) window.laggydash.send({ action: 'bang' }) @game.tweens.remove(obj.move) obj.move = null @game.tweens.remove(obj.jump) obj.jump = null @game.tweens.remove(obj.fade) obj.fade = null obj.kill() addPlayer:(id, name, isPlayer=false)-> x = if isPlayer then 600 else @game.rnd.integerInRange(100, 500) s = if isPlayer then 'runner' else 'wolf' f = if isPlayer then 8 else 12 o = if isPlayer then 0.9 else 1.0 runner = @game.add.sprite(x, 0, s) runner.animations.add('run', [0, 1, 2, 3, 4, 5], f, true) runner.anchor.setTo(0.5, o) runner.onGround = false runner.jump = false runner.bang = false runner.frame = if isPlayer then 3 else 4 runner.target = x runner.id = id if isPlayer w = 20 h = 40 runner.body.setRectangle(w,h,runner.width/2-w/2,runner.height/2-h/2) runner.body.x = runner.x @player_group.add(runner) avatar = @game.add.sprite(x, 475, "@#{name}") avatar.body = null avatar.id = id avatar.name = PI:NAME:<NAME>END_PI avatar.width = 60 avatar.height = 60 avatar.anchor.setTo(0.5, 1.0) avatar.alpha = 0.0 avatar.inputEnabled = true avatar.useHandCursor = true avatar.events.onInputDown.add => if avatar.alpha > 0.5 window.laggydash.showUser(name) @avatar_group.add(avatar) dot = @game.add.sprite(x, avatar.y, "dot") dot.body = null dot.id = id dot.height = 100 dot.anchor.setTo(0.5, 1.0) dot.alpha = 0.0 runner.dot = dot runner.avatar = avatar @avatar_group.add(dot) style = font: "10pt Courier" fill: "#ffffff" label = @game.add.text(x, 480, "@#{name}", style) label.x -= label.width / 2 label.alpha = 0.0 @label_group.add(label) if isPlayer fade = @game.add.tween(avatar) fade.to({ alpha: 0.8 }, 1000, Phaser.Easing.Linear.None, true, 2000) fade = @game.add.tween(dot) fade.to({ alpha: 0.3 }, 1000, Phaser.Easing.Linear.None, true, 2000) fade = @game.add.tween(label) fade.to({ alpha: 1.0 }, 1000, Phaser.Easing.Linear.None, true, 2000) @hero = runner: runner avatar: avatar label: label else @players[id] = runner: runner avatar: avatar label: label showPlayer:=> ids = _.keys(@players) if ids.length == 0 @current = null @prev = null return if @current? && ids.length > 1 @prev = @current ids = _.without(ids, @current) player = @players[@current] fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) fade = @game.add.tween(player.label) fade.to({ alpha: 0.0 }, 1000, Phaser.Easing.Linear.None, true) @current = @game.rnd.pick(ids) player = @players[@current] fade = @game.add.tween(player.avatar) fade.to({ alpha: 0.8 }, 1000, Phaser.Easing.Linear.None, true, 500) fade = @game.add.tween(player.runner.dot) fade.to({ alpha: 0.3 }, 1000, Phaser.Easing.Linear.None, true, 500) fade = @game.add.tween(player.label) fade.to({ alpha: 1.0 }, 1000, Phaser.Easing.Linear.None, true, 500) @timer.remove(event) for event in @timer.events @timer.add(8000, @showPlayer) avatarLoaded:(key)-> @avatar_group.forEach (avatar)=> if avatar.key == "__missing" && key == "@#{avatar.name}" avatar.loadTexture(key) avatar.width = 60 avatar.height = 60 handle:(remote)-> switch remote.action when 'spawn' unless @players[remote.id]? @spawn(remote.id, remote.name) when 'bail' @delPlayer(remote.id) when 'jump' unless @players[remote.id]? @spawn(remote.id, remote.name) @jmpPlayer(remote.id) when 'bang' @diePlayer(remote.id) spawn:(id, name)-> @addPlayer(id, name) @showPlayer() if @current == null delPlayer:(id)-> return unless @players[id]? @players[id].runner.dot.kill() @players[id].runner.kill() @players[id].avatar.kill() @players[id].label.kill() @remPlayer(id) diePlayer:(id)-> return unless @players[id]? player = @players[id].runner @bang(@players[id], player.x, player.y) @remPlayer(id) remPlayer:(id)-> return unless @players[id]? delete(@players[id]) if @current == id @current = null @showPlayer() @prev = null if @prev == id jmpPlayer:(id)-> return unless @players[id]? player = @players[id].runner player.jump = true destroy:-> destroy(@tree0) destroy(@tree1) destroy(@tree2) destroy(@tree3) destroy(@night) destroy(@sky) destroy(@sun) destroy(@cloud) destroy(@grass1) destroy(@grass2) destroy(@runner) destroy(@collect_group) destroy(@player_group) destroy(@avatar_group) destroy(@label_group) destroy(@players) done:=> @game.state.start('splash') LaggyDash.Landscape = Landscape
[ { "context": "#Original JS from Francois Deschenes (https://github.com/fdeschenes/bootstrap-tag)\ncla", "end": 36, "score": 0.9998818039894104, "start": 18, "tag": "NAME", "value": "Francois Deschenes" }, { "context": "al JS from Francois Deschenes (https://github.com/fdeschenes/bootstrap-tag)\nclass Tag\n constructor: ( element", "end": 67, "score": 0.9993653893470764, "start": 57, "tag": "USERNAME", "value": "fdeschenes" } ]
lib/assets/javascripts/bootstrap-tag.js.coffee
zherk/bootstrap-tag
0
#Original JS from Francois Deschenes (https://github.com/fdeschenes/bootstrap-tag) class Tag constructor: ( element, options ) -> this.element = $(element) this.options = $.extend(true, {}, $.fn.tag.defaults, options) this.values = $.grep($.map(this.element.val().split(','), $.trim), ( value ) -> value.length > 0 ) this.show() show: -> that = this that.element.parent().prepend(that.element.detach().hide()) that.element .wrap($('<div class="tags">')) .parent() .on('click', () -> that.input.focus() ) if (that.values.length) $.each(that.values, () -> that.createBadge(this) ) that.input = $('<input type="text">') .attr('placeholder', that.options.placeholder) .insertAfter(that.element) .on('focus', () -> that.element.parent().addClass('tags-hover') ) .on('blur', () -> if (!that.skip) that.process() that.element.parent().removeClass('tags-hover') that.element.siblings('.tag').removeClass('tag-important') that.skip = false ) .on('keydown', ( event ) -> #comma, enter or tab ends a tag if event.keyCode is 188 or event.keyCode is 13 or event.keyCode is 9 if $.trim($(this).val()) and ( !that.element.siblings('.typeahead').length or that.element.siblings('.typeahead').is(':hidden') ) if event.keyCode isnt 9 event.preventDefault() that.process() else if event.keyCode is 188 if ( !that.element.siblings('.typeahead').length || that.element.siblings('.typeahead').is(':hidden') ) event.preventDefault() else that.input.data('typeahead').select() event.stopPropagation() event.preventDefault() else if !$.trim($(this).val()) && event.keyCode is 8 count = that.element.siblings('.tag').length if (count) tag = that.element.siblings('.tag:eq(' + (count - 1) + ')') if (tag.hasClass('tag-important')) that.remove(count - 1) else tag.addClass('tag-important') else that.element.siblings('.tag').removeClass('tag-important') ) .typeahead( hint: true highlight: true minLength: 1 , source: that.options.source #matcher: ( value ) -> # return ~value.toLowerCase().indexOf(this.query.toLowerCase()) && (that.inValues(value) == -1 || that.options.allowDuplicates) ).on('typeahead:selected', (event, suggestion, setName) -> that.add(suggestion.value) ).on('typeahead:closed', () -> $(that.input).val('') ) #$(that.input.data('typeahead').$menu).on('mousedown', () -> # that.skip = true #) this.element.trigger('shown') inValues: ( value ) -> if (this.options.caseInsensitive) index = -1 $.each(this.values, (indexInArray, valueOfElement) -> if valueOfElement.toLowerCase() is value.toLowerCase() index = indexInArray return false ) return index else return $.inArray(value, this.values) createBadge: ( value ) -> that = this $('<span/>', { 'class' : "tag" }) .text(value.toString()) .append($('<button type="button" class="close glyphicon glyphicon-remove"></button>') .on('click', () -> that.remove(that.element.siblings('.tag').index($(this).closest('.tag'))) ) ) .insertBefore(that.element) add: ( value ) -> that = this if ( !that.options.allowDuplicates ) index = that.inValues(value) if index isnt -1 badge = that.element.siblings('.tag:eq(' + index + ')') badge.addClass('tag-warning') setTimeout(() -> $(badge).removeClass('tag-warning') , 500) return this.values.push(value) this.createBadge(value) this.element.val(this.values.join(', ')) this.element.trigger('added', [value]) remove: ( index ) -> if ( index >= 0 ) value = this.values.splice(index, 1) this.element.siblings('.tag:eq(' + index + ')').remove() this.element.val(this.values.join(', ')) this.element.trigger('removed', [value]) process: () -> values = $.grep($.map(this.input.val().split(','), $.trim), ( value ) -> value.length > 0 ) that = this $.each(values, () -> that.add(this) ) this.input.val('') skip: false old = $.fn.tag $.fn.tag = ( option ) -> return this.each(() -> that = $(this) data = that.data('tag') options = typeof option == 'object' && option if (!data) that.data('tag', (data = new Tag(this, options))) if (typeof option is 'string') data[option]() ) $.fn.tag.defaults = allowDuplicates: false, caseInsensitive: true, placeholder: '', source: [] $.fn.tag.Constructor = Tag $.fn.tag.noConflict = () -> $.fn.tag = old return this $(window).on('load', () -> $('[data-provide="tag"]').each(() -> that = $(this) return if (that.data('tag')) that.tag(that.data()) ) )
102921
#Original JS from <NAME> (https://github.com/fdeschenes/bootstrap-tag) class Tag constructor: ( element, options ) -> this.element = $(element) this.options = $.extend(true, {}, $.fn.tag.defaults, options) this.values = $.grep($.map(this.element.val().split(','), $.trim), ( value ) -> value.length > 0 ) this.show() show: -> that = this that.element.parent().prepend(that.element.detach().hide()) that.element .wrap($('<div class="tags">')) .parent() .on('click', () -> that.input.focus() ) if (that.values.length) $.each(that.values, () -> that.createBadge(this) ) that.input = $('<input type="text">') .attr('placeholder', that.options.placeholder) .insertAfter(that.element) .on('focus', () -> that.element.parent().addClass('tags-hover') ) .on('blur', () -> if (!that.skip) that.process() that.element.parent().removeClass('tags-hover') that.element.siblings('.tag').removeClass('tag-important') that.skip = false ) .on('keydown', ( event ) -> #comma, enter or tab ends a tag if event.keyCode is 188 or event.keyCode is 13 or event.keyCode is 9 if $.trim($(this).val()) and ( !that.element.siblings('.typeahead').length or that.element.siblings('.typeahead').is(':hidden') ) if event.keyCode isnt 9 event.preventDefault() that.process() else if event.keyCode is 188 if ( !that.element.siblings('.typeahead').length || that.element.siblings('.typeahead').is(':hidden') ) event.preventDefault() else that.input.data('typeahead').select() event.stopPropagation() event.preventDefault() else if !$.trim($(this).val()) && event.keyCode is 8 count = that.element.siblings('.tag').length if (count) tag = that.element.siblings('.tag:eq(' + (count - 1) + ')') if (tag.hasClass('tag-important')) that.remove(count - 1) else tag.addClass('tag-important') else that.element.siblings('.tag').removeClass('tag-important') ) .typeahead( hint: true highlight: true minLength: 1 , source: that.options.source #matcher: ( value ) -> # return ~value.toLowerCase().indexOf(this.query.toLowerCase()) && (that.inValues(value) == -1 || that.options.allowDuplicates) ).on('typeahead:selected', (event, suggestion, setName) -> that.add(suggestion.value) ).on('typeahead:closed', () -> $(that.input).val('') ) #$(that.input.data('typeahead').$menu).on('mousedown', () -> # that.skip = true #) this.element.trigger('shown') inValues: ( value ) -> if (this.options.caseInsensitive) index = -1 $.each(this.values, (indexInArray, valueOfElement) -> if valueOfElement.toLowerCase() is value.toLowerCase() index = indexInArray return false ) return index else return $.inArray(value, this.values) createBadge: ( value ) -> that = this $('<span/>', { 'class' : "tag" }) .text(value.toString()) .append($('<button type="button" class="close glyphicon glyphicon-remove"></button>') .on('click', () -> that.remove(that.element.siblings('.tag').index($(this).closest('.tag'))) ) ) .insertBefore(that.element) add: ( value ) -> that = this if ( !that.options.allowDuplicates ) index = that.inValues(value) if index isnt -1 badge = that.element.siblings('.tag:eq(' + index + ')') badge.addClass('tag-warning') setTimeout(() -> $(badge).removeClass('tag-warning') , 500) return this.values.push(value) this.createBadge(value) this.element.val(this.values.join(', ')) this.element.trigger('added', [value]) remove: ( index ) -> if ( index >= 0 ) value = this.values.splice(index, 1) this.element.siblings('.tag:eq(' + index + ')').remove() this.element.val(this.values.join(', ')) this.element.trigger('removed', [value]) process: () -> values = $.grep($.map(this.input.val().split(','), $.trim), ( value ) -> value.length > 0 ) that = this $.each(values, () -> that.add(this) ) this.input.val('') skip: false old = $.fn.tag $.fn.tag = ( option ) -> return this.each(() -> that = $(this) data = that.data('tag') options = typeof option == 'object' && option if (!data) that.data('tag', (data = new Tag(this, options))) if (typeof option is 'string') data[option]() ) $.fn.tag.defaults = allowDuplicates: false, caseInsensitive: true, placeholder: '', source: [] $.fn.tag.Constructor = Tag $.fn.tag.noConflict = () -> $.fn.tag = old return this $(window).on('load', () -> $('[data-provide="tag"]').each(() -> that = $(this) return if (that.data('tag')) that.tag(that.data()) ) )
true
#Original JS from PI:NAME:<NAME>END_PI (https://github.com/fdeschenes/bootstrap-tag) class Tag constructor: ( element, options ) -> this.element = $(element) this.options = $.extend(true, {}, $.fn.tag.defaults, options) this.values = $.grep($.map(this.element.val().split(','), $.trim), ( value ) -> value.length > 0 ) this.show() show: -> that = this that.element.parent().prepend(that.element.detach().hide()) that.element .wrap($('<div class="tags">')) .parent() .on('click', () -> that.input.focus() ) if (that.values.length) $.each(that.values, () -> that.createBadge(this) ) that.input = $('<input type="text">') .attr('placeholder', that.options.placeholder) .insertAfter(that.element) .on('focus', () -> that.element.parent().addClass('tags-hover') ) .on('blur', () -> if (!that.skip) that.process() that.element.parent().removeClass('tags-hover') that.element.siblings('.tag').removeClass('tag-important') that.skip = false ) .on('keydown', ( event ) -> #comma, enter or tab ends a tag if event.keyCode is 188 or event.keyCode is 13 or event.keyCode is 9 if $.trim($(this).val()) and ( !that.element.siblings('.typeahead').length or that.element.siblings('.typeahead').is(':hidden') ) if event.keyCode isnt 9 event.preventDefault() that.process() else if event.keyCode is 188 if ( !that.element.siblings('.typeahead').length || that.element.siblings('.typeahead').is(':hidden') ) event.preventDefault() else that.input.data('typeahead').select() event.stopPropagation() event.preventDefault() else if !$.trim($(this).val()) && event.keyCode is 8 count = that.element.siblings('.tag').length if (count) tag = that.element.siblings('.tag:eq(' + (count - 1) + ')') if (tag.hasClass('tag-important')) that.remove(count - 1) else tag.addClass('tag-important') else that.element.siblings('.tag').removeClass('tag-important') ) .typeahead( hint: true highlight: true minLength: 1 , source: that.options.source #matcher: ( value ) -> # return ~value.toLowerCase().indexOf(this.query.toLowerCase()) && (that.inValues(value) == -1 || that.options.allowDuplicates) ).on('typeahead:selected', (event, suggestion, setName) -> that.add(suggestion.value) ).on('typeahead:closed', () -> $(that.input).val('') ) #$(that.input.data('typeahead').$menu).on('mousedown', () -> # that.skip = true #) this.element.trigger('shown') inValues: ( value ) -> if (this.options.caseInsensitive) index = -1 $.each(this.values, (indexInArray, valueOfElement) -> if valueOfElement.toLowerCase() is value.toLowerCase() index = indexInArray return false ) return index else return $.inArray(value, this.values) createBadge: ( value ) -> that = this $('<span/>', { 'class' : "tag" }) .text(value.toString()) .append($('<button type="button" class="close glyphicon glyphicon-remove"></button>') .on('click', () -> that.remove(that.element.siblings('.tag').index($(this).closest('.tag'))) ) ) .insertBefore(that.element) add: ( value ) -> that = this if ( !that.options.allowDuplicates ) index = that.inValues(value) if index isnt -1 badge = that.element.siblings('.tag:eq(' + index + ')') badge.addClass('tag-warning') setTimeout(() -> $(badge).removeClass('tag-warning') , 500) return this.values.push(value) this.createBadge(value) this.element.val(this.values.join(', ')) this.element.trigger('added', [value]) remove: ( index ) -> if ( index >= 0 ) value = this.values.splice(index, 1) this.element.siblings('.tag:eq(' + index + ')').remove() this.element.val(this.values.join(', ')) this.element.trigger('removed', [value]) process: () -> values = $.grep($.map(this.input.val().split(','), $.trim), ( value ) -> value.length > 0 ) that = this $.each(values, () -> that.add(this) ) this.input.val('') skip: false old = $.fn.tag $.fn.tag = ( option ) -> return this.each(() -> that = $(this) data = that.data('tag') options = typeof option == 'object' && option if (!data) that.data('tag', (data = new Tag(this, options))) if (typeof option is 'string') data[option]() ) $.fn.tag.defaults = allowDuplicates: false, caseInsensitive: true, placeholder: '', source: [] $.fn.tag.Constructor = Tag $.fn.tag.noConflict = () -> $.fn.tag = old return this $(window).on('load', () -> $('[data-provide="tag"]').each(() -> that = $(this) return if (that.data('tag')) that.tag(that.data()) ) )
[ { "context": "-7', triode.get_all_superkeys()\n # debug 'µ76777-8', triode.disambiguate_subkey 'n', 'n.'\n debug 'µ", "end": 9930, "score": 0.9302263259887695, "start": 9929, "tag": "KEY", "value": "8" }, { "context": "7-11', triode.get_all_superkeys()\n debug 'µ7887-13', triode.has_superkeys()\n urge 'µ7887-14', '\\n' ", "end": 12078, "score": 0.9757260680198669, "start": 12077, "tag": "KEY", "value": "3" } ]
dev/triode/src/main.test.coffee
loveencounterflow/hengist
0
############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'TRIODE/TESTS/basic' debug = CND.get_logger 'debug', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge help = CND.get_logger 'help', badge warn = CND.get_logger 'warn', badge echo = CND.echo.bind CND #........................................................................................................... jr = JSON.stringify test = require 'guy-test' TRIODE = require '../../../apps/triode' types = new ( require 'intertype' ).Intertype() { isa validate cast type_of } = types #----------------------------------------------------------------------------------------------------------- @[ "basic" ] = ( T, done ) -> triode = TRIODE.new() triode.set 'aluminum', { word: 'aluminum', text: 'a metal', } triode.set 'aluminium', { word: 'aluminium', text: 'a metal', } triode.set 'alumni', { word: 'alumni', text: 'a former student', } triode.set 'alphabet', { word: 'alphabet', text: 'a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: 'a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"a manual calculator"}],["alphabet",{"word":"alphabet","text":"a kind of writing system"}],["alumni",{"word":"alumni","text":"a former student"}],["aluminium",{"word":"aluminium","text":"a metal"}],["aluminum",{"word":"aluminum","text":"a metal"}]],null] ["alu",[["alumni",{"word":"alumni","text":"a former student"}],["aluminium",{"word":"aluminium","text":"a metal"}],["aluminum",{"word":"aluminum","text":"a metal"}]],null] ["alp",[["alphabet",{"word":"alphabet","text":"a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe # urge jr [ probe, result, null, ] resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "sorting 1" ] = ( T, done ) -> triode = TRIODE.new { sort: 'text', } triode.set 'aluminum', { word: 'aluminum', text: '05 a metal', } triode.set 'aluminium', { word: 'aluminium', text: '04 a metal', } triode.set 'alumni', { word: 'alumni', text: '02 a former student', } triode.set 'alphabet', { word: 'alphabet', text: '03 a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: '01 a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alumni",{"word":"alumni","text":"02 a former student"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]],null] ["alu",[["alumni",{"word":"alumni","text":"02 a former student"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]],null] ["alp",[["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "sorting 2" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'aluminum', { word: 'aluminum', text: '05 a metal', } triode.set 'aluminium', { word: 'aluminium', text: '04 a metal', } triode.set 'alumni', { word: 'alumni', text: '02 a former student', } triode.set 'alphabet', { word: 'alphabet', text: '03 a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: '01 a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}],["alumni",{"word":"alumni","text":"02 a former student"}]],null] #! expected result: [["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alumni",{"word":"alumni","text":"02 a former student"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]] ["alu",[["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}],["alumni",{"word":"alumni","text":"02 a former student"}]],null] #! expected result: [["alumni",{"word":"alumni","text":"02 a former student"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]] ["alp",[["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "prefixes by length" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'q', 'っ' triode.set 'n', 'ん' triode.set 'v', 'ゔ' triode.set 'va', 'ゔぁ' triode.set 'vi', 'ゔぃ' triode.set 'vu', 'ゔぅ' triode.set 've', 'ゔぇ' triode.set 'vo', 'ゔぉ' triode.set 'na', 'な' triode.set 'ne', 'ね' triode.set 'ni', 'に' triode.set 'no', 'の' triode.set 'nu', 'ぬ' triode.set 'ya', 'や' triode.set 'yo', 'よ' triode.set 'yu', 'ゆ' triode.set 'nya', 'にゃ' triode.set 'nyo', 'にょ' triode.set 'nyu', 'にゅ' #......................................................................................................... probes_and_matchers = [ [["get_keys_sorted_by_length_asc",[]],["n","q","v","na","ne","ni","no","nu","va","ve","vi","vo","vu","ya","yo","yu","nya","nyo","nyu"],null] [["get_longer_keys",["n"]],["na","ne","ni","no","nu","va","ve","vi","vo","vu","ya","yo","yu","nya","nyo","nyu"],null] [["get_longer_keys",["na"]],["nya","nyo","nyu"],null] [["superkeys_from_key",["n"]],["na","ne","ni","no","nu","nya","nyo","nyu"],null] [["superkeys_from_key",["v"]],["va","ve","vi","vo","vu"],null] [["get_all_superkeys",[]],{"v":["va","ve","vi","vo","vu"],"n":["na","ne","ni","no","nu","nya","nyo","nyu"]},null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ method_name, P, ] = probe result = triode[ method_name ] P... resolve result #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "superkeys" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set '(-1)', '①' triode.set '(-2)', '②' triode.set '(-3)', '③' triode.set '(-4)', '④' triode.set '(-5)', '⑤' triode.set '(-6)', '⑥' triode.set '(-7)', '⑦' triode.set '(-8)', '⑧' triode.set '(-9)', '⑨' triode.set '(-10)', '⑩' triode.set '(', '(' debug result = triode.get_all_superkeys() T.eq result, { '(': [ '(-1)', '(-2)', '(-3)', '(-4)', '(-5)', '(-6)', '(-7)', '(-8)', '(-9)', '(-10)' ] } done() #----------------------------------------------------------------------------------------------------------- @[ "_ demo" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'q', 'っ' triode.set 'n', 'ん' triode.set 'v', 'ゔ' triode.set 'va', 'ゔぁ' triode.set 'vi', 'ゔぃ' triode.set 'vu', 'ゔぅ' triode.set 've', 'ゔぇ' triode.set 'vo', 'ゔぉ' triode.set 'na', 'な' triode.set 'ne', 'ね' triode.set 'ni', 'に' triode.set 'no', 'の' triode.set 'nu', 'ぬ' triode.set 'ya', 'や' triode.set 'yo', 'よ' triode.set 'yu', 'ゆ' triode.set 'nya', 'にゃ' triode.set 'nyo', 'にょ' triode.set 'nyu', 'にゅ' debug 'µ76777-1', triode debug 'µ76777-2', triode.get_keys_sorted_by_length_asc() debug 'µ76777-3', triode.get_longer_keys 'n' # debug 'µ76777-4', triode.get_longer_keys 'na' debug 'µ76777-5', triode.superkeys_from_key 'n' debug 'µ76777-6', triode.superkeys_from_key 'v' debug 'µ76777-7', triode.get_all_superkeys() # debug 'µ76777-8', triode.disambiguate_subkey 'n', 'n.' debug 'µ76777-9', triode # debug 'µ76777-10', triode.superkeys_from_key 'n' # debug 'µ76777-11', triode.superkeys_from_key 'n.' debug 'µ76777-12', triode.has 'n' debug 'µ76777-13', triode.has 'n.' # debug 'µ76777-14', triode.disambiguate_subkey 'n.', 'v' # debug 'µ76777-15', triode.disambiguate_subkey 'a', 'n.' debug 'µ76777-16', triode.disambiguate_subkey 'v', 'v.' debug 'µ76777-17', triode.get_all_superkeys() # debug 'µ76777-18', triode.apply_replacements_recursively 'v' debug 'µ76777-20', triode.apply_replacements_recursively 'n' debug 'µ76777-17', triode.has_superkeys() urge 'µ76777-21', '\n' + triode.replacements_as_js_module_text 'foobar/kana.wsv' replacer = triode.replacements_as_js_function() debug 'µ76777-17', replacer 'ka' debug 'µ76777-17', replacer 'ki' debug 'µ76777-17', replacer 'んa' debug 'µ76777-17', replacer 'んe' debug 'µ76777-17', replacer 'n' debug 'µ76777-17', replacer 'v.' debug 'µ76777-17', replacer 'va' debug 'µ76777-6', triode.superkeys_from_key 'v.' # debug 'µ76777-22', triode done() return null #----------------------------------------------------------------------------------------------------------- @[ "_ demo 2" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'a', 'あ' triode.set 'e', 'え' triode.set 'i', 'い' triode.set 'o', 'お' triode.set 'u', 'う' triode.set 'a=', 'ぁ' triode.set 'i=', 'ぃ' triode.set 'u=', 'ぅ' triode.set 'e=', 'ぇ' triode.set 'o=', 'ぉ' debug 'µ7887-1', triode debug 'µ7887-2', triode.get_keys_sorted_by_length_asc() debug 'µ7887-3', triode.get_longer_keys 'a' # debug 'µ7887-4', triode.get_longer_keys 'na' debug 'µ7887-5', triode.superkeys_from_key 'a' debug 'µ7887-6', triode.get_all_superkeys() debug 'µ7887-7', triode debug 'µ7887-8', triode.has 'a' debug 'µ7887-9', triode.has 'a.' # debug 'µ7887-10', triode.disambiguate_subkey 'v', 'v.' debug 'µ7887-11', triode.get_all_superkeys() debug 'µ7887-12', triode.apply_replacements_recursively 'a' debug 'µ7887-11', triode.get_all_superkeys() debug 'µ7887-13', triode.has_superkeys() urge 'µ7887-14', '\n' + triode.replacements_as_js_module_text 'foobar/kana.wsv' replacer = triode.replacements_as_js_function() debug 'µ7887-15', replacer 'a' debug 'µ7887-16', replacer 'i' debug 'µ7887-17', triode.superkeys_from_key 'v.' # debug 'µ7887-18', triode done() return null ############################################################################################################ unless module.parent? # test @ # test @[ "selector keypatterns" ] # test @[ "select 2" ] # test @[ "_ demo" ] # test @[ "_ demo 2" ] test @[ "superkeys" ]
83584
############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'TRIODE/TESTS/basic' debug = CND.get_logger 'debug', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge help = CND.get_logger 'help', badge warn = CND.get_logger 'warn', badge echo = CND.echo.bind CND #........................................................................................................... jr = JSON.stringify test = require 'guy-test' TRIODE = require '../../../apps/triode' types = new ( require 'intertype' ).Intertype() { isa validate cast type_of } = types #----------------------------------------------------------------------------------------------------------- @[ "basic" ] = ( T, done ) -> triode = TRIODE.new() triode.set 'aluminum', { word: 'aluminum', text: 'a metal', } triode.set 'aluminium', { word: 'aluminium', text: 'a metal', } triode.set 'alumni', { word: 'alumni', text: 'a former student', } triode.set 'alphabet', { word: 'alphabet', text: 'a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: 'a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"a manual calculator"}],["alphabet",{"word":"alphabet","text":"a kind of writing system"}],["alumni",{"word":"alumni","text":"a former student"}],["aluminium",{"word":"aluminium","text":"a metal"}],["aluminum",{"word":"aluminum","text":"a metal"}]],null] ["alu",[["alumni",{"word":"alumni","text":"a former student"}],["aluminium",{"word":"aluminium","text":"a metal"}],["aluminum",{"word":"aluminum","text":"a metal"}]],null] ["alp",[["alphabet",{"word":"alphabet","text":"a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe # urge jr [ probe, result, null, ] resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "sorting 1" ] = ( T, done ) -> triode = TRIODE.new { sort: 'text', } triode.set 'aluminum', { word: 'aluminum', text: '05 a metal', } triode.set 'aluminium', { word: 'aluminium', text: '04 a metal', } triode.set 'alumni', { word: 'alumni', text: '02 a former student', } triode.set 'alphabet', { word: 'alphabet', text: '03 a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: '01 a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alumni",{"word":"alumni","text":"02 a former student"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]],null] ["alu",[["alumni",{"word":"alumni","text":"02 a former student"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]],null] ["alp",[["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "sorting 2" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'aluminum', { word: 'aluminum', text: '05 a metal', } triode.set 'aluminium', { word: 'aluminium', text: '04 a metal', } triode.set 'alumni', { word: 'alumni', text: '02 a former student', } triode.set 'alphabet', { word: 'alphabet', text: '03 a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: '01 a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}],["alumni",{"word":"alumni","text":"02 a former student"}]],null] #! expected result: [["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alumni",{"word":"alumni","text":"02 a former student"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]] ["alu",[["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}],["alumni",{"word":"alumni","text":"02 a former student"}]],null] #! expected result: [["alumni",{"word":"alumni","text":"02 a former student"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]] ["alp",[["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "prefixes by length" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'q', 'っ' triode.set 'n', 'ん' triode.set 'v', 'ゔ' triode.set 'va', 'ゔぁ' triode.set 'vi', 'ゔぃ' triode.set 'vu', 'ゔぅ' triode.set 've', 'ゔぇ' triode.set 'vo', 'ゔぉ' triode.set 'na', 'な' triode.set 'ne', 'ね' triode.set 'ni', 'に' triode.set 'no', 'の' triode.set 'nu', 'ぬ' triode.set 'ya', 'や' triode.set 'yo', 'よ' triode.set 'yu', 'ゆ' triode.set 'nya', 'にゃ' triode.set 'nyo', 'にょ' triode.set 'nyu', 'にゅ' #......................................................................................................... probes_and_matchers = [ [["get_keys_sorted_by_length_asc",[]],["n","q","v","na","ne","ni","no","nu","va","ve","vi","vo","vu","ya","yo","yu","nya","nyo","nyu"],null] [["get_longer_keys",["n"]],["na","ne","ni","no","nu","va","ve","vi","vo","vu","ya","yo","yu","nya","nyo","nyu"],null] [["get_longer_keys",["na"]],["nya","nyo","nyu"],null] [["superkeys_from_key",["n"]],["na","ne","ni","no","nu","nya","nyo","nyu"],null] [["superkeys_from_key",["v"]],["va","ve","vi","vo","vu"],null] [["get_all_superkeys",[]],{"v":["va","ve","vi","vo","vu"],"n":["na","ne","ni","no","nu","nya","nyo","nyu"]},null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ method_name, P, ] = probe result = triode[ method_name ] P... resolve result #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "superkeys" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set '(-1)', '①' triode.set '(-2)', '②' triode.set '(-3)', '③' triode.set '(-4)', '④' triode.set '(-5)', '⑤' triode.set '(-6)', '⑥' triode.set '(-7)', '⑦' triode.set '(-8)', '⑧' triode.set '(-9)', '⑨' triode.set '(-10)', '⑩' triode.set '(', '(' debug result = triode.get_all_superkeys() T.eq result, { '(': [ '(-1)', '(-2)', '(-3)', '(-4)', '(-5)', '(-6)', '(-7)', '(-8)', '(-9)', '(-10)' ] } done() #----------------------------------------------------------------------------------------------------------- @[ "_ demo" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'q', 'っ' triode.set 'n', 'ん' triode.set 'v', 'ゔ' triode.set 'va', 'ゔぁ' triode.set 'vi', 'ゔぃ' triode.set 'vu', 'ゔぅ' triode.set 've', 'ゔぇ' triode.set 'vo', 'ゔぉ' triode.set 'na', 'な' triode.set 'ne', 'ね' triode.set 'ni', 'に' triode.set 'no', 'の' triode.set 'nu', 'ぬ' triode.set 'ya', 'や' triode.set 'yo', 'よ' triode.set 'yu', 'ゆ' triode.set 'nya', 'にゃ' triode.set 'nyo', 'にょ' triode.set 'nyu', 'にゅ' debug 'µ76777-1', triode debug 'µ76777-2', triode.get_keys_sorted_by_length_asc() debug 'µ76777-3', triode.get_longer_keys 'n' # debug 'µ76777-4', triode.get_longer_keys 'na' debug 'µ76777-5', triode.superkeys_from_key 'n' debug 'µ76777-6', triode.superkeys_from_key 'v' debug 'µ76777-7', triode.get_all_superkeys() # debug 'µ76777-<KEY>', triode.disambiguate_subkey 'n', 'n.' debug 'µ76777-9', triode # debug 'µ76777-10', triode.superkeys_from_key 'n' # debug 'µ76777-11', triode.superkeys_from_key 'n.' debug 'µ76777-12', triode.has 'n' debug 'µ76777-13', triode.has 'n.' # debug 'µ76777-14', triode.disambiguate_subkey 'n.', 'v' # debug 'µ76777-15', triode.disambiguate_subkey 'a', 'n.' debug 'µ76777-16', triode.disambiguate_subkey 'v', 'v.' debug 'µ76777-17', triode.get_all_superkeys() # debug 'µ76777-18', triode.apply_replacements_recursively 'v' debug 'µ76777-20', triode.apply_replacements_recursively 'n' debug 'µ76777-17', triode.has_superkeys() urge 'µ76777-21', '\n' + triode.replacements_as_js_module_text 'foobar/kana.wsv' replacer = triode.replacements_as_js_function() debug 'µ76777-17', replacer 'ka' debug 'µ76777-17', replacer 'ki' debug 'µ76777-17', replacer 'んa' debug 'µ76777-17', replacer 'んe' debug 'µ76777-17', replacer 'n' debug 'µ76777-17', replacer 'v.' debug 'µ76777-17', replacer 'va' debug 'µ76777-6', triode.superkeys_from_key 'v.' # debug 'µ76777-22', triode done() return null #----------------------------------------------------------------------------------------------------------- @[ "_ demo 2" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'a', 'あ' triode.set 'e', 'え' triode.set 'i', 'い' triode.set 'o', 'お' triode.set 'u', 'う' triode.set 'a=', 'ぁ' triode.set 'i=', 'ぃ' triode.set 'u=', 'ぅ' triode.set 'e=', 'ぇ' triode.set 'o=', 'ぉ' debug 'µ7887-1', triode debug 'µ7887-2', triode.get_keys_sorted_by_length_asc() debug 'µ7887-3', triode.get_longer_keys 'a' # debug 'µ7887-4', triode.get_longer_keys 'na' debug 'µ7887-5', triode.superkeys_from_key 'a' debug 'µ7887-6', triode.get_all_superkeys() debug 'µ7887-7', triode debug 'µ7887-8', triode.has 'a' debug 'µ7887-9', triode.has 'a.' # debug 'µ7887-10', triode.disambiguate_subkey 'v', 'v.' debug 'µ7887-11', triode.get_all_superkeys() debug 'µ7887-12', triode.apply_replacements_recursively 'a' debug 'µ7887-11', triode.get_all_superkeys() debug 'µ7887-1<KEY>', triode.has_superkeys() urge 'µ7887-14', '\n' + triode.replacements_as_js_module_text 'foobar/kana.wsv' replacer = triode.replacements_as_js_function() debug 'µ7887-15', replacer 'a' debug 'µ7887-16', replacer 'i' debug 'µ7887-17', triode.superkeys_from_key 'v.' # debug 'µ7887-18', triode done() return null ############################################################################################################ unless module.parent? # test @ # test @[ "selector keypatterns" ] # test @[ "select 2" ] # test @[ "_ demo" ] # test @[ "_ demo 2" ] test @[ "superkeys" ]
true
############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'TRIODE/TESTS/basic' debug = CND.get_logger 'debug', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge help = CND.get_logger 'help', badge warn = CND.get_logger 'warn', badge echo = CND.echo.bind CND #........................................................................................................... jr = JSON.stringify test = require 'guy-test' TRIODE = require '../../../apps/triode' types = new ( require 'intertype' ).Intertype() { isa validate cast type_of } = types #----------------------------------------------------------------------------------------------------------- @[ "basic" ] = ( T, done ) -> triode = TRIODE.new() triode.set 'aluminum', { word: 'aluminum', text: 'a metal', } triode.set 'aluminium', { word: 'aluminium', text: 'a metal', } triode.set 'alumni', { word: 'alumni', text: 'a former student', } triode.set 'alphabet', { word: 'alphabet', text: 'a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: 'a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"a manual calculator"}],["alphabet",{"word":"alphabet","text":"a kind of writing system"}],["alumni",{"word":"alumni","text":"a former student"}],["aluminium",{"word":"aluminium","text":"a metal"}],["aluminum",{"word":"aluminum","text":"a metal"}]],null] ["alu",[["alumni",{"word":"alumni","text":"a former student"}],["aluminium",{"word":"aluminium","text":"a metal"}],["aluminum",{"word":"aluminum","text":"a metal"}]],null] ["alp",[["alphabet",{"word":"alphabet","text":"a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe # urge jr [ probe, result, null, ] resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "sorting 1" ] = ( T, done ) -> triode = TRIODE.new { sort: 'text', } triode.set 'aluminum', { word: 'aluminum', text: '05 a metal', } triode.set 'aluminium', { word: 'aluminium', text: '04 a metal', } triode.set 'alumni', { word: 'alumni', text: '02 a former student', } triode.set 'alphabet', { word: 'alphabet', text: '03 a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: '01 a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alumni",{"word":"alumni","text":"02 a former student"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]],null] ["alu",[["alumni",{"word":"alumni","text":"02 a former student"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]],null] ["alp",[["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "sorting 2" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'aluminum', { word: 'aluminum', text: '05 a metal', } triode.set 'aluminium', { word: 'aluminium', text: '04 a metal', } triode.set 'alumni', { word: 'alumni', text: '02 a former student', } triode.set 'alphabet', { word: 'alphabet', text: '03 a kind of writing system', } triode.set 'abacus', { word: 'abacus', text: '01 a manual calculator', } #......................................................................................................... probes_and_matchers = [ ["a",[["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}],["alumni",{"word":"alumni","text":"02 a former student"}]],null] #! expected result: [["abacus",{"word":"abacus","text":"01 a manual calculator"}],["alumni",{"word":"alumni","text":"02 a former student"}],["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]] ["alu",[["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}],["alumni",{"word":"alumni","text":"02 a former student"}]],null] #! expected result: [["alumni",{"word":"alumni","text":"02 a former student"}],["aluminium",{"word":"aluminium","text":"04 a metal"}],["aluminum",{"word":"aluminum","text":"05 a metal"}]] ["alp",[["alphabet",{"word":"alphabet","text":"03 a kind of writing system"}]],null] ["b",[],null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> result = triode.find probe resolve result return null done() return null #----------------------------------------------------------------------------------------------------------- @[ "prefixes by length" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'q', 'っ' triode.set 'n', 'ん' triode.set 'v', 'ゔ' triode.set 'va', 'ゔぁ' triode.set 'vi', 'ゔぃ' triode.set 'vu', 'ゔぅ' triode.set 've', 'ゔぇ' triode.set 'vo', 'ゔぉ' triode.set 'na', 'な' triode.set 'ne', 'ね' triode.set 'ni', 'に' triode.set 'no', 'の' triode.set 'nu', 'ぬ' triode.set 'ya', 'や' triode.set 'yo', 'よ' triode.set 'yu', 'ゆ' triode.set 'nya', 'にゃ' triode.set 'nyo', 'にょ' triode.set 'nyu', 'にゅ' #......................................................................................................... probes_and_matchers = [ [["get_keys_sorted_by_length_asc",[]],["n","q","v","na","ne","ni","no","nu","va","ve","vi","vo","vu","ya","yo","yu","nya","nyo","nyu"],null] [["get_longer_keys",["n"]],["na","ne","ni","no","nu","va","ve","vi","vo","vu","ya","yo","yu","nya","nyo","nyu"],null] [["get_longer_keys",["na"]],["nya","nyo","nyu"],null] [["superkeys_from_key",["n"]],["na","ne","ni","no","nu","nya","nyo","nyu"],null] [["superkeys_from_key",["v"]],["va","ve","vi","vo","vu"],null] [["get_all_superkeys",[]],{"v":["va","ve","vi","vo","vu"],"n":["na","ne","ni","no","nu","nya","nyo","nyu"]},null] ] #......................................................................................................... for [ probe, matcher, error, ] in probes_and_matchers await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) -> [ method_name, P, ] = probe result = triode[ method_name ] P... resolve result #......................................................................................................... done() return null #----------------------------------------------------------------------------------------------------------- @[ "superkeys" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set '(-1)', '①' triode.set '(-2)', '②' triode.set '(-3)', '③' triode.set '(-4)', '④' triode.set '(-5)', '⑤' triode.set '(-6)', '⑥' triode.set '(-7)', '⑦' triode.set '(-8)', '⑧' triode.set '(-9)', '⑨' triode.set '(-10)', '⑩' triode.set '(', '(' debug result = triode.get_all_superkeys() T.eq result, { '(': [ '(-1)', '(-2)', '(-3)', '(-4)', '(-5)', '(-6)', '(-7)', '(-8)', '(-9)', '(-10)' ] } done() #----------------------------------------------------------------------------------------------------------- @[ "_ demo" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'q', 'っ' triode.set 'n', 'ん' triode.set 'v', 'ゔ' triode.set 'va', 'ゔぁ' triode.set 'vi', 'ゔぃ' triode.set 'vu', 'ゔぅ' triode.set 've', 'ゔぇ' triode.set 'vo', 'ゔぉ' triode.set 'na', 'な' triode.set 'ne', 'ね' triode.set 'ni', 'に' triode.set 'no', 'の' triode.set 'nu', 'ぬ' triode.set 'ya', 'や' triode.set 'yo', 'よ' triode.set 'yu', 'ゆ' triode.set 'nya', 'にゃ' triode.set 'nyo', 'にょ' triode.set 'nyu', 'にゅ' debug 'µ76777-1', triode debug 'µ76777-2', triode.get_keys_sorted_by_length_asc() debug 'µ76777-3', triode.get_longer_keys 'n' # debug 'µ76777-4', triode.get_longer_keys 'na' debug 'µ76777-5', triode.superkeys_from_key 'n' debug 'µ76777-6', triode.superkeys_from_key 'v' debug 'µ76777-7', triode.get_all_superkeys() # debug 'µ76777-PI:KEY:<KEY>END_PI', triode.disambiguate_subkey 'n', 'n.' debug 'µ76777-9', triode # debug 'µ76777-10', triode.superkeys_from_key 'n' # debug 'µ76777-11', triode.superkeys_from_key 'n.' debug 'µ76777-12', triode.has 'n' debug 'µ76777-13', triode.has 'n.' # debug 'µ76777-14', triode.disambiguate_subkey 'n.', 'v' # debug 'µ76777-15', triode.disambiguate_subkey 'a', 'n.' debug 'µ76777-16', triode.disambiguate_subkey 'v', 'v.' debug 'µ76777-17', triode.get_all_superkeys() # debug 'µ76777-18', triode.apply_replacements_recursively 'v' debug 'µ76777-20', triode.apply_replacements_recursively 'n' debug 'µ76777-17', triode.has_superkeys() urge 'µ76777-21', '\n' + triode.replacements_as_js_module_text 'foobar/kana.wsv' replacer = triode.replacements_as_js_function() debug 'µ76777-17', replacer 'ka' debug 'µ76777-17', replacer 'ki' debug 'µ76777-17', replacer 'んa' debug 'µ76777-17', replacer 'んe' debug 'µ76777-17', replacer 'n' debug 'µ76777-17', replacer 'v.' debug 'µ76777-17', replacer 'va' debug 'µ76777-6', triode.superkeys_from_key 'v.' # debug 'µ76777-22', triode done() return null #----------------------------------------------------------------------------------------------------------- @[ "_ demo 2" ] = ( T, done ) -> triode = TRIODE.new { sort: true, } triode.set 'a', 'あ' triode.set 'e', 'え' triode.set 'i', 'い' triode.set 'o', 'お' triode.set 'u', 'う' triode.set 'a=', 'ぁ' triode.set 'i=', 'ぃ' triode.set 'u=', 'ぅ' triode.set 'e=', 'ぇ' triode.set 'o=', 'ぉ' debug 'µ7887-1', triode debug 'µ7887-2', triode.get_keys_sorted_by_length_asc() debug 'µ7887-3', triode.get_longer_keys 'a' # debug 'µ7887-4', triode.get_longer_keys 'na' debug 'µ7887-5', triode.superkeys_from_key 'a' debug 'µ7887-6', triode.get_all_superkeys() debug 'µ7887-7', triode debug 'µ7887-8', triode.has 'a' debug 'µ7887-9', triode.has 'a.' # debug 'µ7887-10', triode.disambiguate_subkey 'v', 'v.' debug 'µ7887-11', triode.get_all_superkeys() debug 'µ7887-12', triode.apply_replacements_recursively 'a' debug 'µ7887-11', triode.get_all_superkeys() debug 'µ7887-1PI:KEY:<KEY>END_PI', triode.has_superkeys() urge 'µ7887-14', '\n' + triode.replacements_as_js_module_text 'foobar/kana.wsv' replacer = triode.replacements_as_js_function() debug 'µ7887-15', replacer 'a' debug 'µ7887-16', replacer 'i' debug 'µ7887-17', triode.superkeys_from_key 'v.' # debug 'µ7887-18', triode done() return null ############################################################################################################ unless module.parent? # test @ # test @[ "selector keypatterns" ] # test @[ "select 2" ] # test @[ "_ demo" ] # test @[ "_ demo 2" ] test @[ "superkeys" ]
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affe", "end": 23, "score": 0.5040093064308167, "start": 21, "tag": "NAME", "value": "ty" }, { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999160766601562, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/navbar-mobile.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. topIcon = document.getElementsByClassName('js-navbar-mobile--top-icon') $(document).on 'show.bs.collapse', '.js-navbar-mobile--menu', -> Fade.out topIcon[0] $(document).on 'hide.bs.collapse', '.js-navbar-mobile--menu', -> Fade.in topIcon[0]
2499
# Copyright (c) ppy P<NAME> Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. topIcon = document.getElementsByClassName('js-navbar-mobile--top-icon') $(document).on 'show.bs.collapse', '.js-navbar-mobile--menu', -> Fade.out topIcon[0] $(document).on 'hide.bs.collapse', '.js-navbar-mobile--menu', -> Fade.in topIcon[0]
true
# Copyright (c) ppy PPI:NAME:<NAME>END_PI Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. topIcon = document.getElementsByClassName('js-navbar-mobile--top-icon') $(document).on 'show.bs.collapse', '.js-navbar-mobile--menu', -> Fade.out topIcon[0] $(document).on 'hide.bs.collapse', '.js-navbar-mobile--menu', -> Fade.in topIcon[0]
[ { "context": "###\n backbone-sql.js 0.5.7\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql\n Lice", "end": 57, "score": 0.9982708692550659, "start": 49, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql\n License: MIT (http://www.opensourc", "end": 87, "score": 0.9996774792671204, "start": 79, "tag": "USERNAME", "value": "vidigami" } ]
src/index.coffee
michaelBenin/backbone-sql
1
### backbone-sql.js 0.5.7 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql License: MIT (http://www.opensource.org/licenses/mit-license.php) ### module.exports = sync: require './sync'
77620
### backbone-sql.js 0.5.7 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-sql License: MIT (http://www.opensource.org/licenses/mit-license.php) ### module.exports = sync: require './sync'
true
### backbone-sql.js 0.5.7 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-sql License: MIT (http://www.opensource.org/licenses/mit-license.php) ### module.exports = sync: require './sync'
[ { "context": "# @file lampyridae.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 62, "score": 0.9998774528503418, "start": 48, "tag": "NAME", "value": "Taylor Siviter" }, { "context": "file\n### @file lampyridae.js\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 298, "score": 0.9998832941055298, "start": 284, "tag": "NAME", "value": "Taylor Siviter" } ]
src/lampyridae.coffee
siviter-t/lampyridae.coffee
4
# @file lampyridae.coffee # @Copyright (c) 2016 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. # Header information for the concatenated master file ### @file lampyridae.js # @Copyright (c) 2016 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Create the Lampyridae 'namespace' if possible; throw an error if not. # # @example Create a class in the namespace with global access # class Lampyridae.Foo # ... # # foo = new Lampyridae.Foo # do () -> if not window.Lampyridae? then window.Lampyridae = {} else err = new Error 'Lampyridae namespace could not be assigned. Is there a conflict?' err.name = 'FatalError' throw err ### Default Requirements ### require 'config' require 'util/log' require 'util/checkSupport' ### Conditional Debugging Mode ### # To activate, use `var DEBUG = true` before loading this library! if DEBUG? then if DEBUG "use strict" Lampyridae.Log.isLogging = true Lampyridae.Log.info "Debugging on" Lampyridae.Log.info "Version #{Lampyridae.version}" ### Default Requirements - if everything else checks out! ### require 'core/canvas' require 'particle/particle'
136216
# @file lampyridae.coffee # @Copyright (c) 2016 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. # Header information for the concatenated master file ### @file lampyridae.js # @Copyright (c) 2016 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Create the Lampyridae 'namespace' if possible; throw an error if not. # # @example Create a class in the namespace with global access # class Lampyridae.Foo # ... # # foo = new Lampyridae.Foo # do () -> if not window.Lampyridae? then window.Lampyridae = {} else err = new Error 'Lampyridae namespace could not be assigned. Is there a conflict?' err.name = 'FatalError' throw err ### Default Requirements ### require 'config' require 'util/log' require 'util/checkSupport' ### Conditional Debugging Mode ### # To activate, use `var DEBUG = true` before loading this library! if DEBUG? then if DEBUG "use strict" Lampyridae.Log.isLogging = true Lampyridae.Log.info "Debugging on" Lampyridae.Log.info "Version #{Lampyridae.version}" ### Default Requirements - if everything else checks out! ### require 'core/canvas' require 'particle/particle'
true
# @file lampyridae.coffee # @Copyright (c) 2016 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. # Header information for the concatenated master file ### @file lampyridae.js # @Copyright (c) 2016 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Create the Lampyridae 'namespace' if possible; throw an error if not. # # @example Create a class in the namespace with global access # class Lampyridae.Foo # ... # # foo = new Lampyridae.Foo # do () -> if not window.Lampyridae? then window.Lampyridae = {} else err = new Error 'Lampyridae namespace could not be assigned. Is there a conflict?' err.name = 'FatalError' throw err ### Default Requirements ### require 'config' require 'util/log' require 'util/checkSupport' ### Conditional Debugging Mode ### # To activate, use `var DEBUG = true` before loading this library! if DEBUG? then if DEBUG "use strict" Lampyridae.Log.isLogging = true Lampyridae.Log.info "Debugging on" Lampyridae.Log.info "Version #{Lampyridae.version}" ### Default Requirements - if everything else checks out! ### require 'core/canvas' require 'particle/particle'
[ { "context": " opts.url = @browserConfig.url\n\n logger(\"#{@id} requests #{opts.url}\")\n request opts, (er", "end": 8242, "score": 0.7394710779190063, "start": 8239, "tag": "USERNAME", "value": "@id" }, { "context": ".cookieName\n return cookie.key is 'cb.id'\n )\n if not sessionIdCookie", "end": 8702, "score": 0.9935290813446045, "start": 8697, "tag": "KEY", "value": "cb.id" }, { "context": " through cookie\n # https://gist.github.com/jfromaniello/4087861\n # but it only works for one clien", "end": 15404, "score": 0.9996596574783325, "start": 15392, "tag": "USERNAME", "value": "jfromaniello" } ]
benchmarks/clients/client_process.coffee
bladepan/cloudbrowser
0
{EventEmitter} = require('events') parseUrl = require('url').parse querystring = require('querystring') timers = require('timers') socketio = require('socket.io-client') request = require('request') lodash = require('lodash') debug = require('debug') async = require('async') benchmarkConfig = require('./benchmark_config') routes = require('../../src/server/application_manager/routes') {StatProvider} = require('../../src/shared/stats') Compressor = require('../../src/shared/compressor') logger = debug('cloudbrowser:benchmark') require('http').globalAgent.maxSockets = 65535 class ClientProcess extends EventEmitter constructor: (options) -> {@appInstanceCount, @browserCount, @clientCount, @processId, @optimizeConnection, @batchSize} = options if @browserCount > @clientCount or @appInstanceCount > @browserCount or @appInstanceCount > @clientCount or @appInstanceCount <= 0 msg = "invalid parameter appInstanceCount #{@appInstanceCount} browserCount #{browserCount} clientCount #{clientCount}" console.log(msg) throw new Error(msg) @clientGroups = [] @stats = new StatProvider({ eventProcess : "percentile" }) clientsPerGroup = @clientCount/@appInstanceCount browsersPerGroup = @browserCount/@appInstanceCount talkersPerGroup = options.talkerCount/@appInstanceCount logger("clientsPerGroup #{clientsPerGroup}") debugger for i in [0...@appInstanceCount] by 1 clientGroupOptions = lodash.clone(options) clientGroupOptions.clientCount = clientsPerGroup clientGroupOptions.browserCount = browsersPerGroup clientGroupOptions.talkerCount = talkersPerGroup clientGroupOptions.groupName = "#{@processId}_g#{i}" clientGroupOptions.stats = @stats clientGroup = new ClientGroup(clientGroupOptions) @clientGroups.push(clientGroup) start: ()-> if not @optimizeConnection async.each(@clientGroups, (clientGroup, next)-> clientGroup.start() next() ,(err)=> @emit("started", err) ) return # start clients one by one async.eachLimit(@clientGroups, @batchSize, (clientGroup, next)-> clientGroup.start() clientGroup.once("started", next) , (err)=> @emit("started", err) ) startBenchmark : ()-> if @optimizeConnection async.each(@clientGroups, (clientGroup, next)-> clientGroup.startBenchmark() next() ,(err)-> logger("error when startBenchmark #{err}") if err? ) timeOutCheck : ()-> return if @stopped time = Date.now() for clientGroup in @clientGroups clientGroup.timeOutCheck(time) isStopped:()-> if @stopped return true for clientGroup in @clientGroups if not clientGroup.isStopped() return false @stopped = true return true # clients that share 1 appinstance class ClientGroup extends EventEmitter constructor: (options) -> # append 'c' to client id to make each client id # not a substring of another, so we can just use # serverResponse.substring(clientId) to see if the # client's events has taken effect the server DOM {@browserCount, @clientCount, @talkerCount, @groupName, @optimizeConnection} = options @clients = [] clientsPerBrowser = @clientCount/@browserCount bootstrapClient = null for clientIndex in [0...@clientCount] by 1 clientOptions = lodash.clone(options) clientOptions.id = "#{@groupName}_#{clientIndex}c" if clientIndex%clientsPerBrowser is 0 clientOptions.createBrowser = true if clientIndex is 0 #the very first one will create the Appinstance clientOptions.createAppInstance = true if clientIndex >= @talkerCount clientOptions.silent = true client = new Client(clientOptions) if clientOptions.createBrowser # this client should wait til app instance is created @clients[0].addChild(client) if clientIndex>0 bootstrapClient = client else # co browsing clients bootstrapClient.addChild(client) @clients.push(client) start : ()-> if not @optimizeConnection # the one that starts all @clients[0].start() return @emit("started") async.eachSeries(@clients, (client, next)-> client.start() client.once("clientEngineReady", next) , (err)=> @emit("started", err) ) startBenchmark : ()-> async.each(@clients, (client, next)-> client.emit("startBenchmark") next() , (err)-> logger("#{@groupName} startBenchmark failed #{err}") if err? ) isStopped : ()-> if @stopped return true for client in @clients # ignore silent ones continue if client.silent if not client.stopped return false @stopped = true return true timeOutCheck : (time)-> return if @stopped for client in @clients client.timeOutCheck(time) # eventCount contains the event to create browser class Client extends EventEmitter constructor : (@options) -> # id is a unique client identifier in all client processes {@eventDescriptors, @createBrowser, @silent, @appAddress, @cbhost, @socketioUrl, @stats, @id, @serverLogging, @optimizeConnection} = options @stopped = false @compressor = new Compressor() # some local stats @eventSent = 0 @eventReceived = 0 @expectMet = 0 @eventContext = new benchmarkConfig.EventContext({clientId:@id}) return if @silent @eventQueue = new benchmarkConfig.EventQueue({ descriptors : @eventDescriptors context : @eventContext }) addChild : (child) -> # stop child if it is not started yet @once('stopped', ()-> if not child.started child.stop() ) # if optimizeConnection, do not start child if @optimizeConnection @once('browserconfig', (browserConfig)-> child.browserConfig = browserConfig ) return # start child when browserconfig is ready @once('browserconfig', (browserConfig)-> logger("#{child.id} starting") child.browserConfig = browserConfig child.start() ) start : ()-> @started = true @_initialConnect() _initStartTs : ()-> @startTs = Date.now() _timpeElapsed : ()-> return Date.now() - @startTs _initialConnect : ()-> @_initStartTs() # cookie jar to get session cookie j = request.jar() opts = { url: @appAddress jar: j timeout: @options.timeout } if @createBrowser if not @options.createAppInstance if not @browserConfig? or not @browserConfig.appInstanceId? return @_fatalErrorHandler("No appInstanceId received, maybe parent died.") # create a browser under an app instance opts.url = routes.buildAppInstancePath(@appAddress, @browserConfig.appInstanceId) else if not @browserConfig? or not @browserConfig.url? return @_fatalErrorHandler("No url received, maybe parent died.") opts.url = @browserConfig.url logger("#{@id} requests #{opts.url}") request opts, (err, response, body) => return @_fatalErrorHandler(err) if err? cookies = j.getCookies(@cbhost) if not cookies or cookies.length is 0 return @_fatalErrorHandler("No cookies received.") sessionIdCookie = lodash.find(cookies, (cookie)-> # session cookie's name as in workerConfig.cookieName return cookie.key is 'cb.id' ) if not sessionIdCookie return @_fatalErrorHandler("No session cookie found.") @sessionId = sessionIdCookie.value timeElapsed = @_timpeElapsed() if @createBrowser @browserConfig = {} @browserConfig.browserId = response.headers['x-cb-browserid'] @browserConfig.appId = response.headers['x-cb-appid'] @browserConfig.appInstanceId = response.headers['x-cb-appinstanceid'] # for clients that share browser @browserConfig.url = response.headers['x-cb-url'] if not @browserConfig.appId? or not @browserConfig.browserId? return @_fatalErrorHandler("No browserid detected.") if @createBrowser @stats.add('createBrowser', timeElapsed) if @options.createAppInstance @stats.add('createAppInstance', timeElapsed) # give others opportunity to receive io events timers.setImmediate(()=> logger("#{@id} emit browserConfig #{@browserConfig.url}") # creating socket after children clients send initial requests @emit('browserconfig', @browserConfig) ) logger("#{@id} opened #{@browserConfig.url}") @stats.add('initialPage', timeElapsed) if not @options.createBrowserOnly timers.setImmediate(()=> @_createSocket() @_initialSocketIo() ) else timers.setImmediate(()=> @emit("clientEngineReady") @stopped = true ) _initialSocketIo : ()-> @_initStartTs() @socket.on('connect', ()=> @stats.add('socketIoConnect', @_timpeElapsed()) @socket.emit('auth', @browserConfig.appId, @browserConfig.appInstanceId, @browserConfig.browserId) @_initStartTs() @socket.on('SetConfig',()-> # do nothing ) ) @socket.once 'PageLoaded', (nodes, registeredEventTypes, clientComponents, compressionTable) => @stats.add('pageLoaded', @_timpeElapsed()) if compressionTable? for k, v of compressionTable @compressor.register(k, v) do (k, v)=> @socket.on(v, ()=> @_serverEventHandler(k, arguments) ) @socket.on('newSymbol', (original, compressed)=> @compressor.register(original, compressed) do (original, compressed) => @socket.on(compressed, ()=> @_serverEventHandler(original, arguments) ) ) if not @silent if @optimizeConnection @once('startBenchmark', ()=> @_nextEvent() ) else timers.setImmediate(()=> @_nextEvent() ) #logger("#{@id} emit clientEngineReady") @clientEngineReady=true @emit("clientEngineReady") _nextEvent : ()-> if @stopped return nextEvent = @eventQueue.poll() if not nextEvent @stats.addCounter('finished') return @stop() if @waitStart? @stats.add('wait', Date.now()- @waitStart) @waitStart = null # stop and expect if nextEvent.type is 'expect' @expect = nextEvent @expectStartTime = Date.now() else waitDuration = nextEvent.getWaitDuration() fireNextEvent = ()=> @stats.addCounter('clientEvent') nextEvent.emitEvent(@socket) @eventSent++ @_nextEvent() if waitDuration <=0 # do not put fireNextEvent to the event loop, # or the server response might come earlier than expect setting up. # a better way to do this would be setting up expect first. fireNextEvent() else setTimeout(fireNextEvent, waitDuration) _serverEventHandler : (eventName, args)-> @stats.addCounter('serverEvent') return if @stopped # dosomething special for batch events.... if eventName is 'batch' batchedEvents = args[0] clientId = args[1] # add artificial pauseRendering, resume Rendering event. @_matchExpect('pauseRendering', []) for ievent in batchedEvents ieventName = ievent[0] original = @compressor.decompress(ieventName) if original? ieventName = original eventArgs = [] index = 1 while typeof ievent[index] isnt 'undefined' eventArgs.push(ievent[index]) index++ @_matchExpect(ieventName, eventArgs) @_matchExpect('resumeRendering', [clientId]) else @_matchExpect(eventName, args) _matchExpect : (eventName, args)-> @eventReceived++ if @expect? expectResult = @expect.expect(eventName, args) if expectResult is 2 now = Date.now() @stats.add('eventProcess', now - @expectStartTime) @expectMet++ waitDuration = @expect.getWaitDuration() @expect = null @expectStartTime = null if waitDuration <=0 setImmediate(@_nextEvent.bind(@)) else @waitStart = now setTimeout(@_nextEvent.bind(@), waitDuration) timeOutCheck : (time)-> return if not @started or @stopped if not @clientEngineReady and @startTs? and time-@startTs > @options.timeout return @_fatalErrorHandler("Timeout while bootstrap clientengine") if @expectStartTime? and time - @expectStartTime > @options.timeout @_fatalErrorHandler("Timeout while expecting #{@expect.getExpectingEventName()}, eventSent #{@eventSent}, eventReceived #{@eventReceived}, expectMet #{@expectMet}") _createSocket : ()-> @_initStartTs() # pass the session id through url, there is a way to pass through cookie # https://gist.github.com/jfromaniello/4087861 # but it only works for one client instance. # session id from cookie is already urlencoded, so no need to encode here queryString = "referer=#{encodeURIComponent(@browserConfig.url)}&cb.id=#{@sessionId}" if @serverLogging queryString += "&logging=#{@serverLogging}&browserId=#{@browserConfig.browserId}" # this is a synchronized call, seems no actual connection established # at this point. # forceNew is mandatory or socket-io will reuse a connection!!!! @socket = socketio(@socketioUrl, { query: queryString forceNew:true timeout: @options.timeout }) @stats.add('socketCreateTime', @_timpeElapsed()) @socket.on('error',(err)=> @_fatalErrorHandler("SoketIoError #{err}") ) @socket.on('cberror',(err)=> @_fatalErrorHandler("cberror #{err}") ) @socket.on('disconnect', ()=> @_fatalErrorHandler("disconnected at the other end") ) _fatalErrorHandler : (@error)-> errorMsg="#{@id} #{error}" logger(errorMsg) @stats.addCounter('fatalError', errorMsg) if not @clientEngineReady # the clientEngineReady will always be triggered, # so the benchmark could go on even some clients fail @emit("clientEngineReady") @stop() stop : () -> @expect = null @expectStartTime = null @stopped = true # do not disconnect right away, continue counting server side events @emit('stopped') toJSON : ()-> result = {} for k, v of @ if typeof v is 'function' or k is 'socket' or k.indexOf('_') is 0 continue result[k] = v return result options = { appInstanceCount : { full : 'appinstance-count' default : 10 type : 'number' help : 'count of appinstances created on server side.' }, browserCount : { full : 'browser-count' default : 50 type : 'number' help : 'count of virtual browsers created on server side.' }, clientCount : { full : 'client-count' default : 50*5 type : 'number' help : 'number of clients connected to server' }, appAddress : { full : 'app-address' default : 'http://localhost:3000/benchmark' help : 'benchmark application address' }, timeout : { env : 'CB_TIMEOUT' default : 1000*30 type : 'number' help : 'connection timeout in ms' }, processId : { full : 'process-id' default : 'p0' }, serverLogging : { full : 'server-logging' default : false type : 'boolean' }, optimizeConnection : { full : 'optimize-connection' default : true type : 'boolean' }, batchSize : { full : "batch-size" default : 20 type : "number" }, configFile : { full : 'configFile' default : '#{__dirname}/chat_benchmark.conf' }, talkerCount : { full : 'talkerCount' type : 'number' help : 'how many clients actually send events, by default it equals clientCount' }, createBrowserOnly : { env : 'CB_CREATEVBONLY' default : false type : 'boolean' help : 'stop after the initial page loaded' } } opts = require('../../src/shared/commandline_parser').parse(options, process.argv) if opts.appAddress? parsedUrl = parseUrl(opts.appAddress) # as request cookie domain opts.cbhost = "http://#{parsedUrl.hostname}" # host contains port opts.socketioUrl = "http://#{parsedUrl.host}" if not opts.talkerCount? opts.talkerCount = opts.clientCount logger("options #{JSON.stringify(opts)}") eventDescriptorReader = new benchmarkConfig.EventDescriptorsReader({fileName:opts.configFile}) SysMon = require('../../src/server/sys_mon') sysMon = new SysMon({ interval : 5000 }) clientProcess = null benchmarkFinished = false resultLogger = debug("cloudbrowser:benchmark:result") simpleStatTempFunc = (statsObj)-> return if not statsObj? {eventProcess, serverEvent, clientEvent} = statsObj msg = '' if eventProcess? msg += "eventProcess: rate #{eventProcess.rate}, avg #{eventProcess.avg} , current #{eventProcess.current}\n eventProcess: totalRate #{eventProcess.totalRate}, totalAvg #{eventProcess.totalAvg}, count #{eventProcess.count}\n eventProcess: max #{eventProcess.max}, min #{eventProcess.min}\n" if eventProcess['100%']? msg += "eventProcess: 90% #{eventProcess['90%']}, 95% #{eventProcess['95%']}, 99% #{eventProcess['99%']}\n" if serverEvent? msg += "serverEvent: rate #{serverEvent.rate}, count #{serverEvent.count};\n" if clientEvent? msg += "clientEvent: rate #{clientEvent.rate}, count #{clientEvent.count};\n" return msg reportStats = (statsObj)-> resultLogger(JSON.stringify(statsObj)) resultLogger(simpleStatTempFunc(statsObj)) async.waterfall([ (next)-> eventDescriptorReader.read(next) (eventDescriptors, next)-> opts.eventDescriptors = eventDescriptors clientProcess = new ClientProcess(opts) clientProcess.start() clientProcess.once("started", next) intervalObj = setInterval(()-> reportStats(clientProcess.stats.report2()) return if benchmarkFinished benchmarkFinished = clientProcess.isStopped() if not benchmarkFinished clientProcess.timeOutCheck() else logger("benchmark finished, wait #{opts.timeout}ms to exit.") # receive all the server side events setTimeout(()-> clearInterval(intervalObj) sysMon.stop() resultLogger "stopped" process.exit(1) , opts.timeout) , 3000 ) (next)-> resultLogger("start benchmark...") clientProcess.startBenchmark() next() ], (err)-> console.log("clientProcess #{opts.processId} error #{err}") if err? ) process.on('SIGTERM',()-> if clientProcess and not benchmarkFinished reportStats(clientProcess.stats.report2()) resultLogger "terminated" process.exit(1) )
75543
{EventEmitter} = require('events') parseUrl = require('url').parse querystring = require('querystring') timers = require('timers') socketio = require('socket.io-client') request = require('request') lodash = require('lodash') debug = require('debug') async = require('async') benchmarkConfig = require('./benchmark_config') routes = require('../../src/server/application_manager/routes') {StatProvider} = require('../../src/shared/stats') Compressor = require('../../src/shared/compressor') logger = debug('cloudbrowser:benchmark') require('http').globalAgent.maxSockets = 65535 class ClientProcess extends EventEmitter constructor: (options) -> {@appInstanceCount, @browserCount, @clientCount, @processId, @optimizeConnection, @batchSize} = options if @browserCount > @clientCount or @appInstanceCount > @browserCount or @appInstanceCount > @clientCount or @appInstanceCount <= 0 msg = "invalid parameter appInstanceCount #{@appInstanceCount} browserCount #{browserCount} clientCount #{clientCount}" console.log(msg) throw new Error(msg) @clientGroups = [] @stats = new StatProvider({ eventProcess : "percentile" }) clientsPerGroup = @clientCount/@appInstanceCount browsersPerGroup = @browserCount/@appInstanceCount talkersPerGroup = options.talkerCount/@appInstanceCount logger("clientsPerGroup #{clientsPerGroup}") debugger for i in [0...@appInstanceCount] by 1 clientGroupOptions = lodash.clone(options) clientGroupOptions.clientCount = clientsPerGroup clientGroupOptions.browserCount = browsersPerGroup clientGroupOptions.talkerCount = talkersPerGroup clientGroupOptions.groupName = "#{@processId}_g#{i}" clientGroupOptions.stats = @stats clientGroup = new ClientGroup(clientGroupOptions) @clientGroups.push(clientGroup) start: ()-> if not @optimizeConnection async.each(@clientGroups, (clientGroup, next)-> clientGroup.start() next() ,(err)=> @emit("started", err) ) return # start clients one by one async.eachLimit(@clientGroups, @batchSize, (clientGroup, next)-> clientGroup.start() clientGroup.once("started", next) , (err)=> @emit("started", err) ) startBenchmark : ()-> if @optimizeConnection async.each(@clientGroups, (clientGroup, next)-> clientGroup.startBenchmark() next() ,(err)-> logger("error when startBenchmark #{err}") if err? ) timeOutCheck : ()-> return if @stopped time = Date.now() for clientGroup in @clientGroups clientGroup.timeOutCheck(time) isStopped:()-> if @stopped return true for clientGroup in @clientGroups if not clientGroup.isStopped() return false @stopped = true return true # clients that share 1 appinstance class ClientGroup extends EventEmitter constructor: (options) -> # append 'c' to client id to make each client id # not a substring of another, so we can just use # serverResponse.substring(clientId) to see if the # client's events has taken effect the server DOM {@browserCount, @clientCount, @talkerCount, @groupName, @optimizeConnection} = options @clients = [] clientsPerBrowser = @clientCount/@browserCount bootstrapClient = null for clientIndex in [0...@clientCount] by 1 clientOptions = lodash.clone(options) clientOptions.id = "#{@groupName}_#{clientIndex}c" if clientIndex%clientsPerBrowser is 0 clientOptions.createBrowser = true if clientIndex is 0 #the very first one will create the Appinstance clientOptions.createAppInstance = true if clientIndex >= @talkerCount clientOptions.silent = true client = new Client(clientOptions) if clientOptions.createBrowser # this client should wait til app instance is created @clients[0].addChild(client) if clientIndex>0 bootstrapClient = client else # co browsing clients bootstrapClient.addChild(client) @clients.push(client) start : ()-> if not @optimizeConnection # the one that starts all @clients[0].start() return @emit("started") async.eachSeries(@clients, (client, next)-> client.start() client.once("clientEngineReady", next) , (err)=> @emit("started", err) ) startBenchmark : ()-> async.each(@clients, (client, next)-> client.emit("startBenchmark") next() , (err)-> logger("#{@groupName} startBenchmark failed #{err}") if err? ) isStopped : ()-> if @stopped return true for client in @clients # ignore silent ones continue if client.silent if not client.stopped return false @stopped = true return true timeOutCheck : (time)-> return if @stopped for client in @clients client.timeOutCheck(time) # eventCount contains the event to create browser class Client extends EventEmitter constructor : (@options) -> # id is a unique client identifier in all client processes {@eventDescriptors, @createBrowser, @silent, @appAddress, @cbhost, @socketioUrl, @stats, @id, @serverLogging, @optimizeConnection} = options @stopped = false @compressor = new Compressor() # some local stats @eventSent = 0 @eventReceived = 0 @expectMet = 0 @eventContext = new benchmarkConfig.EventContext({clientId:@id}) return if @silent @eventQueue = new benchmarkConfig.EventQueue({ descriptors : @eventDescriptors context : @eventContext }) addChild : (child) -> # stop child if it is not started yet @once('stopped', ()-> if not child.started child.stop() ) # if optimizeConnection, do not start child if @optimizeConnection @once('browserconfig', (browserConfig)-> child.browserConfig = browserConfig ) return # start child when browserconfig is ready @once('browserconfig', (browserConfig)-> logger("#{child.id} starting") child.browserConfig = browserConfig child.start() ) start : ()-> @started = true @_initialConnect() _initStartTs : ()-> @startTs = Date.now() _timpeElapsed : ()-> return Date.now() - @startTs _initialConnect : ()-> @_initStartTs() # cookie jar to get session cookie j = request.jar() opts = { url: @appAddress jar: j timeout: @options.timeout } if @createBrowser if not @options.createAppInstance if not @browserConfig? or not @browserConfig.appInstanceId? return @_fatalErrorHandler("No appInstanceId received, maybe parent died.") # create a browser under an app instance opts.url = routes.buildAppInstancePath(@appAddress, @browserConfig.appInstanceId) else if not @browserConfig? or not @browserConfig.url? return @_fatalErrorHandler("No url received, maybe parent died.") opts.url = @browserConfig.url logger("#{@id} requests #{opts.url}") request opts, (err, response, body) => return @_fatalErrorHandler(err) if err? cookies = j.getCookies(@cbhost) if not cookies or cookies.length is 0 return @_fatalErrorHandler("No cookies received.") sessionIdCookie = lodash.find(cookies, (cookie)-> # session cookie's name as in workerConfig.cookieName return cookie.key is '<KEY>' ) if not sessionIdCookie return @_fatalErrorHandler("No session cookie found.") @sessionId = sessionIdCookie.value timeElapsed = @_timpeElapsed() if @createBrowser @browserConfig = {} @browserConfig.browserId = response.headers['x-cb-browserid'] @browserConfig.appId = response.headers['x-cb-appid'] @browserConfig.appInstanceId = response.headers['x-cb-appinstanceid'] # for clients that share browser @browserConfig.url = response.headers['x-cb-url'] if not @browserConfig.appId? or not @browserConfig.browserId? return @_fatalErrorHandler("No browserid detected.") if @createBrowser @stats.add('createBrowser', timeElapsed) if @options.createAppInstance @stats.add('createAppInstance', timeElapsed) # give others opportunity to receive io events timers.setImmediate(()=> logger("#{@id} emit browserConfig #{@browserConfig.url}") # creating socket after children clients send initial requests @emit('browserconfig', @browserConfig) ) logger("#{@id} opened #{@browserConfig.url}") @stats.add('initialPage', timeElapsed) if not @options.createBrowserOnly timers.setImmediate(()=> @_createSocket() @_initialSocketIo() ) else timers.setImmediate(()=> @emit("clientEngineReady") @stopped = true ) _initialSocketIo : ()-> @_initStartTs() @socket.on('connect', ()=> @stats.add('socketIoConnect', @_timpeElapsed()) @socket.emit('auth', @browserConfig.appId, @browserConfig.appInstanceId, @browserConfig.browserId) @_initStartTs() @socket.on('SetConfig',()-> # do nothing ) ) @socket.once 'PageLoaded', (nodes, registeredEventTypes, clientComponents, compressionTable) => @stats.add('pageLoaded', @_timpeElapsed()) if compressionTable? for k, v of compressionTable @compressor.register(k, v) do (k, v)=> @socket.on(v, ()=> @_serverEventHandler(k, arguments) ) @socket.on('newSymbol', (original, compressed)=> @compressor.register(original, compressed) do (original, compressed) => @socket.on(compressed, ()=> @_serverEventHandler(original, arguments) ) ) if not @silent if @optimizeConnection @once('startBenchmark', ()=> @_nextEvent() ) else timers.setImmediate(()=> @_nextEvent() ) #logger("#{@id} emit clientEngineReady") @clientEngineReady=true @emit("clientEngineReady") _nextEvent : ()-> if @stopped return nextEvent = @eventQueue.poll() if not nextEvent @stats.addCounter('finished') return @stop() if @waitStart? @stats.add('wait', Date.now()- @waitStart) @waitStart = null # stop and expect if nextEvent.type is 'expect' @expect = nextEvent @expectStartTime = Date.now() else waitDuration = nextEvent.getWaitDuration() fireNextEvent = ()=> @stats.addCounter('clientEvent') nextEvent.emitEvent(@socket) @eventSent++ @_nextEvent() if waitDuration <=0 # do not put fireNextEvent to the event loop, # or the server response might come earlier than expect setting up. # a better way to do this would be setting up expect first. fireNextEvent() else setTimeout(fireNextEvent, waitDuration) _serverEventHandler : (eventName, args)-> @stats.addCounter('serverEvent') return if @stopped # dosomething special for batch events.... if eventName is 'batch' batchedEvents = args[0] clientId = args[1] # add artificial pauseRendering, resume Rendering event. @_matchExpect('pauseRendering', []) for ievent in batchedEvents ieventName = ievent[0] original = @compressor.decompress(ieventName) if original? ieventName = original eventArgs = [] index = 1 while typeof ievent[index] isnt 'undefined' eventArgs.push(ievent[index]) index++ @_matchExpect(ieventName, eventArgs) @_matchExpect('resumeRendering', [clientId]) else @_matchExpect(eventName, args) _matchExpect : (eventName, args)-> @eventReceived++ if @expect? expectResult = @expect.expect(eventName, args) if expectResult is 2 now = Date.now() @stats.add('eventProcess', now - @expectStartTime) @expectMet++ waitDuration = @expect.getWaitDuration() @expect = null @expectStartTime = null if waitDuration <=0 setImmediate(@_nextEvent.bind(@)) else @waitStart = now setTimeout(@_nextEvent.bind(@), waitDuration) timeOutCheck : (time)-> return if not @started or @stopped if not @clientEngineReady and @startTs? and time-@startTs > @options.timeout return @_fatalErrorHandler("Timeout while bootstrap clientengine") if @expectStartTime? and time - @expectStartTime > @options.timeout @_fatalErrorHandler("Timeout while expecting #{@expect.getExpectingEventName()}, eventSent #{@eventSent}, eventReceived #{@eventReceived}, expectMet #{@expectMet}") _createSocket : ()-> @_initStartTs() # pass the session id through url, there is a way to pass through cookie # https://gist.github.com/jfromaniello/4087861 # but it only works for one client instance. # session id from cookie is already urlencoded, so no need to encode here queryString = "referer=#{encodeURIComponent(@browserConfig.url)}&cb.id=#{@sessionId}" if @serverLogging queryString += "&logging=#{@serverLogging}&browserId=#{@browserConfig.browserId}" # this is a synchronized call, seems no actual connection established # at this point. # forceNew is mandatory or socket-io will reuse a connection!!!! @socket = socketio(@socketioUrl, { query: queryString forceNew:true timeout: @options.timeout }) @stats.add('socketCreateTime', @_timpeElapsed()) @socket.on('error',(err)=> @_fatalErrorHandler("SoketIoError #{err}") ) @socket.on('cberror',(err)=> @_fatalErrorHandler("cberror #{err}") ) @socket.on('disconnect', ()=> @_fatalErrorHandler("disconnected at the other end") ) _fatalErrorHandler : (@error)-> errorMsg="#{@id} #{error}" logger(errorMsg) @stats.addCounter('fatalError', errorMsg) if not @clientEngineReady # the clientEngineReady will always be triggered, # so the benchmark could go on even some clients fail @emit("clientEngineReady") @stop() stop : () -> @expect = null @expectStartTime = null @stopped = true # do not disconnect right away, continue counting server side events @emit('stopped') toJSON : ()-> result = {} for k, v of @ if typeof v is 'function' or k is 'socket' or k.indexOf('_') is 0 continue result[k] = v return result options = { appInstanceCount : { full : 'appinstance-count' default : 10 type : 'number' help : 'count of appinstances created on server side.' }, browserCount : { full : 'browser-count' default : 50 type : 'number' help : 'count of virtual browsers created on server side.' }, clientCount : { full : 'client-count' default : 50*5 type : 'number' help : 'number of clients connected to server' }, appAddress : { full : 'app-address' default : 'http://localhost:3000/benchmark' help : 'benchmark application address' }, timeout : { env : 'CB_TIMEOUT' default : 1000*30 type : 'number' help : 'connection timeout in ms' }, processId : { full : 'process-id' default : 'p0' }, serverLogging : { full : 'server-logging' default : false type : 'boolean' }, optimizeConnection : { full : 'optimize-connection' default : true type : 'boolean' }, batchSize : { full : "batch-size" default : 20 type : "number" }, configFile : { full : 'configFile' default : '#{__dirname}/chat_benchmark.conf' }, talkerCount : { full : 'talkerCount' type : 'number' help : 'how many clients actually send events, by default it equals clientCount' }, createBrowserOnly : { env : 'CB_CREATEVBONLY' default : false type : 'boolean' help : 'stop after the initial page loaded' } } opts = require('../../src/shared/commandline_parser').parse(options, process.argv) if opts.appAddress? parsedUrl = parseUrl(opts.appAddress) # as request cookie domain opts.cbhost = "http://#{parsedUrl.hostname}" # host contains port opts.socketioUrl = "http://#{parsedUrl.host}" if not opts.talkerCount? opts.talkerCount = opts.clientCount logger("options #{JSON.stringify(opts)}") eventDescriptorReader = new benchmarkConfig.EventDescriptorsReader({fileName:opts.configFile}) SysMon = require('../../src/server/sys_mon') sysMon = new SysMon({ interval : 5000 }) clientProcess = null benchmarkFinished = false resultLogger = debug("cloudbrowser:benchmark:result") simpleStatTempFunc = (statsObj)-> return if not statsObj? {eventProcess, serverEvent, clientEvent} = statsObj msg = '' if eventProcess? msg += "eventProcess: rate #{eventProcess.rate}, avg #{eventProcess.avg} , current #{eventProcess.current}\n eventProcess: totalRate #{eventProcess.totalRate}, totalAvg #{eventProcess.totalAvg}, count #{eventProcess.count}\n eventProcess: max #{eventProcess.max}, min #{eventProcess.min}\n" if eventProcess['100%']? msg += "eventProcess: 90% #{eventProcess['90%']}, 95% #{eventProcess['95%']}, 99% #{eventProcess['99%']}\n" if serverEvent? msg += "serverEvent: rate #{serverEvent.rate}, count #{serverEvent.count};\n" if clientEvent? msg += "clientEvent: rate #{clientEvent.rate}, count #{clientEvent.count};\n" return msg reportStats = (statsObj)-> resultLogger(JSON.stringify(statsObj)) resultLogger(simpleStatTempFunc(statsObj)) async.waterfall([ (next)-> eventDescriptorReader.read(next) (eventDescriptors, next)-> opts.eventDescriptors = eventDescriptors clientProcess = new ClientProcess(opts) clientProcess.start() clientProcess.once("started", next) intervalObj = setInterval(()-> reportStats(clientProcess.stats.report2()) return if benchmarkFinished benchmarkFinished = clientProcess.isStopped() if not benchmarkFinished clientProcess.timeOutCheck() else logger("benchmark finished, wait #{opts.timeout}ms to exit.") # receive all the server side events setTimeout(()-> clearInterval(intervalObj) sysMon.stop() resultLogger "stopped" process.exit(1) , opts.timeout) , 3000 ) (next)-> resultLogger("start benchmark...") clientProcess.startBenchmark() next() ], (err)-> console.log("clientProcess #{opts.processId} error #{err}") if err? ) process.on('SIGTERM',()-> if clientProcess and not benchmarkFinished reportStats(clientProcess.stats.report2()) resultLogger "terminated" process.exit(1) )
true
{EventEmitter} = require('events') parseUrl = require('url').parse querystring = require('querystring') timers = require('timers') socketio = require('socket.io-client') request = require('request') lodash = require('lodash') debug = require('debug') async = require('async') benchmarkConfig = require('./benchmark_config') routes = require('../../src/server/application_manager/routes') {StatProvider} = require('../../src/shared/stats') Compressor = require('../../src/shared/compressor') logger = debug('cloudbrowser:benchmark') require('http').globalAgent.maxSockets = 65535 class ClientProcess extends EventEmitter constructor: (options) -> {@appInstanceCount, @browserCount, @clientCount, @processId, @optimizeConnection, @batchSize} = options if @browserCount > @clientCount or @appInstanceCount > @browserCount or @appInstanceCount > @clientCount or @appInstanceCount <= 0 msg = "invalid parameter appInstanceCount #{@appInstanceCount} browserCount #{browserCount} clientCount #{clientCount}" console.log(msg) throw new Error(msg) @clientGroups = [] @stats = new StatProvider({ eventProcess : "percentile" }) clientsPerGroup = @clientCount/@appInstanceCount browsersPerGroup = @browserCount/@appInstanceCount talkersPerGroup = options.talkerCount/@appInstanceCount logger("clientsPerGroup #{clientsPerGroup}") debugger for i in [0...@appInstanceCount] by 1 clientGroupOptions = lodash.clone(options) clientGroupOptions.clientCount = clientsPerGroup clientGroupOptions.browserCount = browsersPerGroup clientGroupOptions.talkerCount = talkersPerGroup clientGroupOptions.groupName = "#{@processId}_g#{i}" clientGroupOptions.stats = @stats clientGroup = new ClientGroup(clientGroupOptions) @clientGroups.push(clientGroup) start: ()-> if not @optimizeConnection async.each(@clientGroups, (clientGroup, next)-> clientGroup.start() next() ,(err)=> @emit("started", err) ) return # start clients one by one async.eachLimit(@clientGroups, @batchSize, (clientGroup, next)-> clientGroup.start() clientGroup.once("started", next) , (err)=> @emit("started", err) ) startBenchmark : ()-> if @optimizeConnection async.each(@clientGroups, (clientGroup, next)-> clientGroup.startBenchmark() next() ,(err)-> logger("error when startBenchmark #{err}") if err? ) timeOutCheck : ()-> return if @stopped time = Date.now() for clientGroup in @clientGroups clientGroup.timeOutCheck(time) isStopped:()-> if @stopped return true for clientGroup in @clientGroups if not clientGroup.isStopped() return false @stopped = true return true # clients that share 1 appinstance class ClientGroup extends EventEmitter constructor: (options) -> # append 'c' to client id to make each client id # not a substring of another, so we can just use # serverResponse.substring(clientId) to see if the # client's events has taken effect the server DOM {@browserCount, @clientCount, @talkerCount, @groupName, @optimizeConnection} = options @clients = [] clientsPerBrowser = @clientCount/@browserCount bootstrapClient = null for clientIndex in [0...@clientCount] by 1 clientOptions = lodash.clone(options) clientOptions.id = "#{@groupName}_#{clientIndex}c" if clientIndex%clientsPerBrowser is 0 clientOptions.createBrowser = true if clientIndex is 0 #the very first one will create the Appinstance clientOptions.createAppInstance = true if clientIndex >= @talkerCount clientOptions.silent = true client = new Client(clientOptions) if clientOptions.createBrowser # this client should wait til app instance is created @clients[0].addChild(client) if clientIndex>0 bootstrapClient = client else # co browsing clients bootstrapClient.addChild(client) @clients.push(client) start : ()-> if not @optimizeConnection # the one that starts all @clients[0].start() return @emit("started") async.eachSeries(@clients, (client, next)-> client.start() client.once("clientEngineReady", next) , (err)=> @emit("started", err) ) startBenchmark : ()-> async.each(@clients, (client, next)-> client.emit("startBenchmark") next() , (err)-> logger("#{@groupName} startBenchmark failed #{err}") if err? ) isStopped : ()-> if @stopped return true for client in @clients # ignore silent ones continue if client.silent if not client.stopped return false @stopped = true return true timeOutCheck : (time)-> return if @stopped for client in @clients client.timeOutCheck(time) # eventCount contains the event to create browser class Client extends EventEmitter constructor : (@options) -> # id is a unique client identifier in all client processes {@eventDescriptors, @createBrowser, @silent, @appAddress, @cbhost, @socketioUrl, @stats, @id, @serverLogging, @optimizeConnection} = options @stopped = false @compressor = new Compressor() # some local stats @eventSent = 0 @eventReceived = 0 @expectMet = 0 @eventContext = new benchmarkConfig.EventContext({clientId:@id}) return if @silent @eventQueue = new benchmarkConfig.EventQueue({ descriptors : @eventDescriptors context : @eventContext }) addChild : (child) -> # stop child if it is not started yet @once('stopped', ()-> if not child.started child.stop() ) # if optimizeConnection, do not start child if @optimizeConnection @once('browserconfig', (browserConfig)-> child.browserConfig = browserConfig ) return # start child when browserconfig is ready @once('browserconfig', (browserConfig)-> logger("#{child.id} starting") child.browserConfig = browserConfig child.start() ) start : ()-> @started = true @_initialConnect() _initStartTs : ()-> @startTs = Date.now() _timpeElapsed : ()-> return Date.now() - @startTs _initialConnect : ()-> @_initStartTs() # cookie jar to get session cookie j = request.jar() opts = { url: @appAddress jar: j timeout: @options.timeout } if @createBrowser if not @options.createAppInstance if not @browserConfig? or not @browserConfig.appInstanceId? return @_fatalErrorHandler("No appInstanceId received, maybe parent died.") # create a browser under an app instance opts.url = routes.buildAppInstancePath(@appAddress, @browserConfig.appInstanceId) else if not @browserConfig? or not @browserConfig.url? return @_fatalErrorHandler("No url received, maybe parent died.") opts.url = @browserConfig.url logger("#{@id} requests #{opts.url}") request opts, (err, response, body) => return @_fatalErrorHandler(err) if err? cookies = j.getCookies(@cbhost) if not cookies or cookies.length is 0 return @_fatalErrorHandler("No cookies received.") sessionIdCookie = lodash.find(cookies, (cookie)-> # session cookie's name as in workerConfig.cookieName return cookie.key is 'PI:KEY:<KEY>END_PI' ) if not sessionIdCookie return @_fatalErrorHandler("No session cookie found.") @sessionId = sessionIdCookie.value timeElapsed = @_timpeElapsed() if @createBrowser @browserConfig = {} @browserConfig.browserId = response.headers['x-cb-browserid'] @browserConfig.appId = response.headers['x-cb-appid'] @browserConfig.appInstanceId = response.headers['x-cb-appinstanceid'] # for clients that share browser @browserConfig.url = response.headers['x-cb-url'] if not @browserConfig.appId? or not @browserConfig.browserId? return @_fatalErrorHandler("No browserid detected.") if @createBrowser @stats.add('createBrowser', timeElapsed) if @options.createAppInstance @stats.add('createAppInstance', timeElapsed) # give others opportunity to receive io events timers.setImmediate(()=> logger("#{@id} emit browserConfig #{@browserConfig.url}") # creating socket after children clients send initial requests @emit('browserconfig', @browserConfig) ) logger("#{@id} opened #{@browserConfig.url}") @stats.add('initialPage', timeElapsed) if not @options.createBrowserOnly timers.setImmediate(()=> @_createSocket() @_initialSocketIo() ) else timers.setImmediate(()=> @emit("clientEngineReady") @stopped = true ) _initialSocketIo : ()-> @_initStartTs() @socket.on('connect', ()=> @stats.add('socketIoConnect', @_timpeElapsed()) @socket.emit('auth', @browserConfig.appId, @browserConfig.appInstanceId, @browserConfig.browserId) @_initStartTs() @socket.on('SetConfig',()-> # do nothing ) ) @socket.once 'PageLoaded', (nodes, registeredEventTypes, clientComponents, compressionTable) => @stats.add('pageLoaded', @_timpeElapsed()) if compressionTable? for k, v of compressionTable @compressor.register(k, v) do (k, v)=> @socket.on(v, ()=> @_serverEventHandler(k, arguments) ) @socket.on('newSymbol', (original, compressed)=> @compressor.register(original, compressed) do (original, compressed) => @socket.on(compressed, ()=> @_serverEventHandler(original, arguments) ) ) if not @silent if @optimizeConnection @once('startBenchmark', ()=> @_nextEvent() ) else timers.setImmediate(()=> @_nextEvent() ) #logger("#{@id} emit clientEngineReady") @clientEngineReady=true @emit("clientEngineReady") _nextEvent : ()-> if @stopped return nextEvent = @eventQueue.poll() if not nextEvent @stats.addCounter('finished') return @stop() if @waitStart? @stats.add('wait', Date.now()- @waitStart) @waitStart = null # stop and expect if nextEvent.type is 'expect' @expect = nextEvent @expectStartTime = Date.now() else waitDuration = nextEvent.getWaitDuration() fireNextEvent = ()=> @stats.addCounter('clientEvent') nextEvent.emitEvent(@socket) @eventSent++ @_nextEvent() if waitDuration <=0 # do not put fireNextEvent to the event loop, # or the server response might come earlier than expect setting up. # a better way to do this would be setting up expect first. fireNextEvent() else setTimeout(fireNextEvent, waitDuration) _serverEventHandler : (eventName, args)-> @stats.addCounter('serverEvent') return if @stopped # dosomething special for batch events.... if eventName is 'batch' batchedEvents = args[0] clientId = args[1] # add artificial pauseRendering, resume Rendering event. @_matchExpect('pauseRendering', []) for ievent in batchedEvents ieventName = ievent[0] original = @compressor.decompress(ieventName) if original? ieventName = original eventArgs = [] index = 1 while typeof ievent[index] isnt 'undefined' eventArgs.push(ievent[index]) index++ @_matchExpect(ieventName, eventArgs) @_matchExpect('resumeRendering', [clientId]) else @_matchExpect(eventName, args) _matchExpect : (eventName, args)-> @eventReceived++ if @expect? expectResult = @expect.expect(eventName, args) if expectResult is 2 now = Date.now() @stats.add('eventProcess', now - @expectStartTime) @expectMet++ waitDuration = @expect.getWaitDuration() @expect = null @expectStartTime = null if waitDuration <=0 setImmediate(@_nextEvent.bind(@)) else @waitStart = now setTimeout(@_nextEvent.bind(@), waitDuration) timeOutCheck : (time)-> return if not @started or @stopped if not @clientEngineReady and @startTs? and time-@startTs > @options.timeout return @_fatalErrorHandler("Timeout while bootstrap clientengine") if @expectStartTime? and time - @expectStartTime > @options.timeout @_fatalErrorHandler("Timeout while expecting #{@expect.getExpectingEventName()}, eventSent #{@eventSent}, eventReceived #{@eventReceived}, expectMet #{@expectMet}") _createSocket : ()-> @_initStartTs() # pass the session id through url, there is a way to pass through cookie # https://gist.github.com/jfromaniello/4087861 # but it only works for one client instance. # session id from cookie is already urlencoded, so no need to encode here queryString = "referer=#{encodeURIComponent(@browserConfig.url)}&cb.id=#{@sessionId}" if @serverLogging queryString += "&logging=#{@serverLogging}&browserId=#{@browserConfig.browserId}" # this is a synchronized call, seems no actual connection established # at this point. # forceNew is mandatory or socket-io will reuse a connection!!!! @socket = socketio(@socketioUrl, { query: queryString forceNew:true timeout: @options.timeout }) @stats.add('socketCreateTime', @_timpeElapsed()) @socket.on('error',(err)=> @_fatalErrorHandler("SoketIoError #{err}") ) @socket.on('cberror',(err)=> @_fatalErrorHandler("cberror #{err}") ) @socket.on('disconnect', ()=> @_fatalErrorHandler("disconnected at the other end") ) _fatalErrorHandler : (@error)-> errorMsg="#{@id} #{error}" logger(errorMsg) @stats.addCounter('fatalError', errorMsg) if not @clientEngineReady # the clientEngineReady will always be triggered, # so the benchmark could go on even some clients fail @emit("clientEngineReady") @stop() stop : () -> @expect = null @expectStartTime = null @stopped = true # do not disconnect right away, continue counting server side events @emit('stopped') toJSON : ()-> result = {} for k, v of @ if typeof v is 'function' or k is 'socket' or k.indexOf('_') is 0 continue result[k] = v return result options = { appInstanceCount : { full : 'appinstance-count' default : 10 type : 'number' help : 'count of appinstances created on server side.' }, browserCount : { full : 'browser-count' default : 50 type : 'number' help : 'count of virtual browsers created on server side.' }, clientCount : { full : 'client-count' default : 50*5 type : 'number' help : 'number of clients connected to server' }, appAddress : { full : 'app-address' default : 'http://localhost:3000/benchmark' help : 'benchmark application address' }, timeout : { env : 'CB_TIMEOUT' default : 1000*30 type : 'number' help : 'connection timeout in ms' }, processId : { full : 'process-id' default : 'p0' }, serverLogging : { full : 'server-logging' default : false type : 'boolean' }, optimizeConnection : { full : 'optimize-connection' default : true type : 'boolean' }, batchSize : { full : "batch-size" default : 20 type : "number" }, configFile : { full : 'configFile' default : '#{__dirname}/chat_benchmark.conf' }, talkerCount : { full : 'talkerCount' type : 'number' help : 'how many clients actually send events, by default it equals clientCount' }, createBrowserOnly : { env : 'CB_CREATEVBONLY' default : false type : 'boolean' help : 'stop after the initial page loaded' } } opts = require('../../src/shared/commandline_parser').parse(options, process.argv) if opts.appAddress? parsedUrl = parseUrl(opts.appAddress) # as request cookie domain opts.cbhost = "http://#{parsedUrl.hostname}" # host contains port opts.socketioUrl = "http://#{parsedUrl.host}" if not opts.talkerCount? opts.talkerCount = opts.clientCount logger("options #{JSON.stringify(opts)}") eventDescriptorReader = new benchmarkConfig.EventDescriptorsReader({fileName:opts.configFile}) SysMon = require('../../src/server/sys_mon') sysMon = new SysMon({ interval : 5000 }) clientProcess = null benchmarkFinished = false resultLogger = debug("cloudbrowser:benchmark:result") simpleStatTempFunc = (statsObj)-> return if not statsObj? {eventProcess, serverEvent, clientEvent} = statsObj msg = '' if eventProcess? msg += "eventProcess: rate #{eventProcess.rate}, avg #{eventProcess.avg} , current #{eventProcess.current}\n eventProcess: totalRate #{eventProcess.totalRate}, totalAvg #{eventProcess.totalAvg}, count #{eventProcess.count}\n eventProcess: max #{eventProcess.max}, min #{eventProcess.min}\n" if eventProcess['100%']? msg += "eventProcess: 90% #{eventProcess['90%']}, 95% #{eventProcess['95%']}, 99% #{eventProcess['99%']}\n" if serverEvent? msg += "serverEvent: rate #{serverEvent.rate}, count #{serverEvent.count};\n" if clientEvent? msg += "clientEvent: rate #{clientEvent.rate}, count #{clientEvent.count};\n" return msg reportStats = (statsObj)-> resultLogger(JSON.stringify(statsObj)) resultLogger(simpleStatTempFunc(statsObj)) async.waterfall([ (next)-> eventDescriptorReader.read(next) (eventDescriptors, next)-> opts.eventDescriptors = eventDescriptors clientProcess = new ClientProcess(opts) clientProcess.start() clientProcess.once("started", next) intervalObj = setInterval(()-> reportStats(clientProcess.stats.report2()) return if benchmarkFinished benchmarkFinished = clientProcess.isStopped() if not benchmarkFinished clientProcess.timeOutCheck() else logger("benchmark finished, wait #{opts.timeout}ms to exit.") # receive all the server side events setTimeout(()-> clearInterval(intervalObj) sysMon.stop() resultLogger "stopped" process.exit(1) , opts.timeout) , 3000 ) (next)-> resultLogger("start benchmark...") clientProcess.startBenchmark() next() ], (err)-> console.log("clientProcess #{opts.processId} error #{err}") if err? ) process.on('SIGTERM',()-> if clientProcess and not benchmarkFinished reportStats(clientProcess.stats.report2()) resultLogger "terminated" process.exit(1) )
[ { "context": "egister', new LocalStrategy({\n usernameField: 'username'\n passwordField: 'password'\n passReqToCallb", "end": 339, "score": 0.9993149042129517, "start": 331, "tag": "USERNAME", "value": "username" }, { "context": " usernameField: 'username'\n passwordField: 'password'\n passReqToCallback: true\n}, (req, username, p", "end": 369, "score": 0.9990572333335876, "start": 361, "tag": "PASSWORD", "value": "password" }, { "context": " email: req.body.email\n username: username\n password: password\n },", "end": 829, "score": 0.9981715679168701, "start": 821, "tag": "USERNAME", "value": "username" }, { "context": " username: username\n password: password\n }, (err) ->\n if err\n ", "end": 864, "score": 0.9991479516029358, "start": 856, "tag": "PASSWORD", "value": "password" }, { "context": " 'login', new LocalStrategy({\n usernameField: 'username'\n passwordField: 'password'\n}, (username, pass", "end": 1073, "score": 0.9991791844367981, "start": 1065, "tag": "USERNAME", "value": "username" }, { "context": " usernameField: 'username'\n passwordField: 'password'\n}, (username, password, done) ->\n UserRepo.ge", "end": 1103, "score": 0.9993269443511963, "start": 1095, "tag": "PASSWORD", "value": "password" } ]
passport.coffee
jastribl/stir-server
0
LocalStrategy = require('passport-local').Strategy passport = require('passport') UserRepo = require('./data/UserRepo') passport.serializeUser (user, done) -> done(null, user.id) passport.deserializeUser (_user, done) -> UserRepo.getUserById _user, done passport.use 'register', new LocalStrategy({ usernameField: 'username' passwordField: 'password' passReqToCallback: true }, (req, username, password, done) -> UserRepo.getUserByUserName username, (err, user) -> if err done(err) else if user? done(null, false, 'That username is already taken.') else UserRepo.createNewUser { firstName: req.body.firstName lastName: req.body.lastName email: req.body.email username: username password: password }, (err) -> if err done(err) else done(null, true) ) passport.use 'login', new LocalStrategy({ usernameField: 'username' passwordField: 'password' }, (username, password, done) -> UserRepo.getUserByUserName username, (err, user) -> if err done(err) else if not user? done(null, false, 'This user was not found! Check your spelling.') else if not user.validPassword(password) done(null, false, 'Oops! Wrong password.') else done(null, user) )
156216
LocalStrategy = require('passport-local').Strategy passport = require('passport') UserRepo = require('./data/UserRepo') passport.serializeUser (user, done) -> done(null, user.id) passport.deserializeUser (_user, done) -> UserRepo.getUserById _user, done passport.use 'register', new LocalStrategy({ usernameField: 'username' passwordField: '<PASSWORD>' passReqToCallback: true }, (req, username, password, done) -> UserRepo.getUserByUserName username, (err, user) -> if err done(err) else if user? done(null, false, 'That username is already taken.') else UserRepo.createNewUser { firstName: req.body.firstName lastName: req.body.lastName email: req.body.email username: username password: <PASSWORD> }, (err) -> if err done(err) else done(null, true) ) passport.use 'login', new LocalStrategy({ usernameField: 'username' passwordField: '<PASSWORD>' }, (username, password, done) -> UserRepo.getUserByUserName username, (err, user) -> if err done(err) else if not user? done(null, false, 'This user was not found! Check your spelling.') else if not user.validPassword(password) done(null, false, 'Oops! Wrong password.') else done(null, user) )
true
LocalStrategy = require('passport-local').Strategy passport = require('passport') UserRepo = require('./data/UserRepo') passport.serializeUser (user, done) -> done(null, user.id) passport.deserializeUser (_user, done) -> UserRepo.getUserById _user, done passport.use 'register', new LocalStrategy({ usernameField: 'username' passwordField: 'PI:PASSWORD:<PASSWORD>END_PI' passReqToCallback: true }, (req, username, password, done) -> UserRepo.getUserByUserName username, (err, user) -> if err done(err) else if user? done(null, false, 'That username is already taken.') else UserRepo.createNewUser { firstName: req.body.firstName lastName: req.body.lastName email: req.body.email username: username password: PI:PASSWORD:<PASSWORD>END_PI }, (err) -> if err done(err) else done(null, true) ) passport.use 'login', new LocalStrategy({ usernameField: 'username' passwordField: 'PI:PASSWORD:<PASSWORD>END_PI' }, (username, password, done) -> UserRepo.getUserByUserName username, (err, user) -> if err done(err) else if not user? done(null, false, 'This user was not found! Check your spelling.') else if not user.validPassword(password) done(null, false, 'Oops! Wrong password.') else done(null, user) )
[ { "context": "cache-loop'\n\nkeys_cache = new CacheLoop {\n key: 'mkay:apikeys'\n interval: '10 seconds'\n use: ((cb) ->", "end": 242, "score": 0.9777781963348389, "start": 238, "tag": "KEY", "value": "mkay" } ]
core/internal.iced
tosadvisor/link-shortener
7
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 _ = require('wegweg')({ globals: off }) basic_auth = require 'basic-auth' valid_key = conf.api.auth CacheLoop = require 'taky-cache-loop' keys_cache = new CacheLoop { key: 'mkay:apikeys' interval: '10 seconds' use: ((cb) -> if !conf.mongo then return cb null, [] await col('apikeys').find {active:on}, defer e,r if !e and r?.length cb null, (_.map r, (x) -> x.key) else cb null, [] ) } internal = {} internal.middleware = (req,res,next) -> ignore = [ '/_/' ] for x in ignore return next() if req.path.startsWith(x) if req.path in ___public_routes if !process.env.SILENCE log.warn 'AUTH_MIDDLEWARE', "Allowing request #{req.method} #{req.path} (public route)" return next() forbid = -> req.no_stack = yes res.status 403 return next new Error 'Unauthorized' {user, pass} = basic_auth(req) || ({ user: req.headers['x-auth-username'] pass: req.headers['x-auth-password'] }) pass = user if user and !pass if pass and pass.contains('token:') pass = pass.split(':').pop() if !pass then return forbid() try return next() if pass in keys_cache.val() if !pass or pass isnt valid_key return forbid() next() module.exports = internal
16138
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 _ = require('wegweg')({ globals: off }) basic_auth = require 'basic-auth' valid_key = conf.api.auth CacheLoop = require 'taky-cache-loop' keys_cache = new CacheLoop { key: '<KEY>:apikeys' interval: '10 seconds' use: ((cb) -> if !conf.mongo then return cb null, [] await col('apikeys').find {active:on}, defer e,r if !e and r?.length cb null, (_.map r, (x) -> x.key) else cb null, [] ) } internal = {} internal.middleware = (req,res,next) -> ignore = [ '/_/' ] for x in ignore return next() if req.path.startsWith(x) if req.path in ___public_routes if !process.env.SILENCE log.warn 'AUTH_MIDDLEWARE', "Allowing request #{req.method} #{req.path} (public route)" return next() forbid = -> req.no_stack = yes res.status 403 return next new Error 'Unauthorized' {user, pass} = basic_auth(req) || ({ user: req.headers['x-auth-username'] pass: req.headers['x-auth-password'] }) pass = user if user and !pass if pass and pass.contains('token:') pass = pass.split(':').pop() if !pass then return forbid() try return next() if pass in keys_cache.val() if !pass or pass isnt valid_key return forbid() next() module.exports = internal
true
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 _ = require('wegweg')({ globals: off }) basic_auth = require 'basic-auth' valid_key = conf.api.auth CacheLoop = require 'taky-cache-loop' keys_cache = new CacheLoop { key: 'PI:KEY:<KEY>END_PI:apikeys' interval: '10 seconds' use: ((cb) -> if !conf.mongo then return cb null, [] await col('apikeys').find {active:on}, defer e,r if !e and r?.length cb null, (_.map r, (x) -> x.key) else cb null, [] ) } internal = {} internal.middleware = (req,res,next) -> ignore = [ '/_/' ] for x in ignore return next() if req.path.startsWith(x) if req.path in ___public_routes if !process.env.SILENCE log.warn 'AUTH_MIDDLEWARE', "Allowing request #{req.method} #{req.path} (public route)" return next() forbid = -> req.no_stack = yes res.status 403 return next new Error 'Unauthorized' {user, pass} = basic_auth(req) || ({ user: req.headers['x-auth-username'] pass: req.headers['x-auth-password'] }) pass = user if user and !pass if pass and pass.contains('token:') pass = pass.split(':').pop() if !pass then return forbid() try return next() if pass in keys_cache.val() if !pass or pass isnt valid_key return forbid() next() module.exports = internal
[ { "context": "Validate closing bracket location in JSX\n# @author Yannick Croissant\n###\n'use strict'\n\n{has} = require 'lodash'\ndocsUr", "end": 89, "score": 0.9998561143875122, "start": 72, "tag": "NAME", "value": "Yannick Croissant" } ]
src/rules/jsx-closing-bracket-location.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Validate closing bracket location in JSX # @author Yannick Croissant ### 'use strict' {has} = require 'lodash' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Validate closing bracket location in JSX' category: 'Stylistic Issues' recommended: no url: docsUrl 'jsx-closing-bracket-location' fixable: 'code' schema: [ oneOf: [ enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' ] , type: 'object' properties: location: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' ] additionalProperties: no , type: 'object' properties: nonEmpty: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' no ] selfClosing: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' no ] additionalProperties: no ] ] create: (context) -> MESSAGE = 'The closing bracket must be {{location}}{{details}}' MESSAGE_LOCATION = 'after-props': 'placed after the last prop' 'after-tag': 'placed after the opening tag' 'props-aligned': 'aligned with the last prop' # 'tag-aligned': 'aligned with the opening tag' 'line-aligned': 'aligned with the line containing the opening tag' DEFAULT_LOCATION = 'line-aligned' sourceCode = context.getSourceCode() config = context.options[0] options = nonEmpty: DEFAULT_LOCATION selfClosing: DEFAULT_LOCATION if typeof config is 'string' # simple shorthand [1, 'something'] options.nonEmpty = config options.selfClosing = config else if typeof config is 'object' # [1, {location: 'something'}] (back-compat) if has config, 'location' options.nonEmpty = config.location options.selfClosing = config.location # [1, {nonEmpty: 'something'}] if has config, 'nonEmpty' then options.nonEmpty = config.nonEmpty # [1, {selfClosing: 'something'}] if has config, 'selfClosing' then options.selfClosing = config.selfClosing ###* # Get expected location for the closing bracket # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @return {String} Expected location for the closing bracket ### getExpectedLocation = (tokens) -> requested = if tokens.selfClosing options.selfClosing else options.nonEmpty # Is always after the opening tag if there is no props unless tokens.lastProp? 'after-tag' # Is always after the last prop if this one is on the same line as the opening bracket else if tokens.opening.line is tokens.lastProp.lastLine 'after-props' # Aligning with prop that's on opening line can cause indentation error else if ( tokens.opening.line is tokens.lastProp.firstLine and requested is 'props-aligned' ) 'line-aligned' # Else use configuration dependent on selfClosing property else requested ###* # Get the correct 0-indexed column for the closing bracket, given the # expected location. # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @return {?Number} The correct column for the closing bracket, or null ### getCorrectColumn = (tokens, expectedLocation) -> switch expectedLocation when 'props-aligned' return tokens.lastProp.column when 'tag-aligned' return tokens.opening.column when 'line-aligned' return tokens.openingStartOfLine.column else return null ###* # Check if the closing bracket is correctly located # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @return {Boolean} True if the closing bracket is correctly located, false if not ### hasCorrectLocation = (tokens, expectedLocation) -> switch expectedLocation when 'after-tag' return tokens.tag.line is tokens.closing.line when 'after-props' return tokens.lastProp.lastLine is tokens.closing.line when 'props-aligned', 'tag-aligned', 'line-aligned' correctColumn = getCorrectColumn tokens, expectedLocation return correctColumn is tokens.closing.column else return yes ###* # Get the characters used for indentation on the line to be matched # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @param {Number} correctColumn Expected column for the closing bracket # @return {String} The characters used for indentation ### getIndentation = (tokens, expectedLocation, correctColumn) -> spaces = [] switch expectedLocation when 'props-aligned' indentation = /^\s*/.exec(sourceCode.lines[tokens.lastProp.firstLine - 1])[0] when 'tag-aligned', 'line-aligned' indentation = /^\s*/.exec(sourceCode.lines[tokens.opening.line - 1])[0] else indentation = '' if indentation.length + 1 < correctColumn # Non-whitespace characters were included in the column offset spaces = new Array +correctColumn + 1 - indentation.length indentation + spaces.join ' ' ###* # Get the locations of the opening bracket, closing bracket, last prop, and # start of opening line. # @param {ASTNode} node The node to check # @return {Object} Locations of the opening bracket, closing bracket, last # prop and start of opening line. ### getTokensLocations = (node) -> opening = sourceCode.getFirstToken(node).loc.start closing = sourceCode.getLastTokens(node, if node.selfClosing then 2 else 1)[0].loc .start tag = sourceCode.getFirstToken(node.name).loc.start if node.attributes.length lastProp = node.attributes[node.attributes.length - 1] lastProp = column: sourceCode.getFirstToken(lastProp).loc.start.column firstLine: sourceCode.getFirstToken(lastProp).loc.start.line lastLine: sourceCode.getLastToken(lastProp).loc.end.line openingLine = sourceCode.lines[opening.line - 1] openingStartOfLine = column: /^\s*/.exec(openingLine)[0].length line: opening.line { tag opening closing lastProp selfClosing: node.selfClosing openingStartOfLine } ###* # Get an unique ID for a given JSXOpeningElement # # @param {ASTNode} node The AST node being checked. # @returns {String} Unique ID (based on its range) ### getOpeningElementId = (node) -> node.range.join ':' lastAttributeNode = {} JSXAttribute: (node) -> lastAttributeNode[getOpeningElementId node.parent] = node JSXSpreadAttribute: (node) -> lastAttributeNode[getOpeningElementId node.parent] = node 'JSXOpeningElement:exit': (node) -> attributeNode = lastAttributeNode[getOpeningElementId node] cachedLastAttributeEndPos = if attributeNode attributeNode.range[1] else null tokens = getTokensLocations node expectedLocation = getExpectedLocation tokens return if hasCorrectLocation tokens, expectedLocation data = location: MESSAGE_LOCATION[expectedLocation], details: '' correctColumn = getCorrectColumn tokens, expectedLocation unless correctColumn is null expectedNextLine = tokens.lastProp and tokens.lastProp.lastLine is tokens.closing.line data.details = " (expected column #{correctColumn + 1}#{ if expectedNextLine then ' on the next line)' else ')' }" context.report { node loc: tokens.closing message: MESSAGE data fix: (fixer) -> closingTag = if tokens.selfClosing then '/>' else '>' switch expectedLocation when 'after-tag' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] (if expectedNextLine then '\n' else '') + closingTag ) if cachedLastAttributeEndPos return fixer.replaceTextRange( [node.name.range[1], node.range[1]] (if expectedNextLine then '\n' else ' ') + closingTag ) when 'after-props' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] (if expectedNextLine then '\n' else '') + closingTag ) when 'props-aligned', 'tag-aligned', 'line-aligned' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] "\n#{getIndentation( tokens expectedLocation correctColumn )}#{closingTag}" ) else return yes }
79422
###* # @fileoverview Validate closing bracket location in JSX # @author <NAME> ### 'use strict' {has} = require 'lodash' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Validate closing bracket location in JSX' category: 'Stylistic Issues' recommended: no url: docsUrl 'jsx-closing-bracket-location' fixable: 'code' schema: [ oneOf: [ enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' ] , type: 'object' properties: location: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' ] additionalProperties: no , type: 'object' properties: nonEmpty: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' no ] selfClosing: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' no ] additionalProperties: no ] ] create: (context) -> MESSAGE = 'The closing bracket must be {{location}}{{details}}' MESSAGE_LOCATION = 'after-props': 'placed after the last prop' 'after-tag': 'placed after the opening tag' 'props-aligned': 'aligned with the last prop' # 'tag-aligned': 'aligned with the opening tag' 'line-aligned': 'aligned with the line containing the opening tag' DEFAULT_LOCATION = 'line-aligned' sourceCode = context.getSourceCode() config = context.options[0] options = nonEmpty: DEFAULT_LOCATION selfClosing: DEFAULT_LOCATION if typeof config is 'string' # simple shorthand [1, 'something'] options.nonEmpty = config options.selfClosing = config else if typeof config is 'object' # [1, {location: 'something'}] (back-compat) if has config, 'location' options.nonEmpty = config.location options.selfClosing = config.location # [1, {nonEmpty: 'something'}] if has config, 'nonEmpty' then options.nonEmpty = config.nonEmpty # [1, {selfClosing: 'something'}] if has config, 'selfClosing' then options.selfClosing = config.selfClosing ###* # Get expected location for the closing bracket # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @return {String} Expected location for the closing bracket ### getExpectedLocation = (tokens) -> requested = if tokens.selfClosing options.selfClosing else options.nonEmpty # Is always after the opening tag if there is no props unless tokens.lastProp? 'after-tag' # Is always after the last prop if this one is on the same line as the opening bracket else if tokens.opening.line is tokens.lastProp.lastLine 'after-props' # Aligning with prop that's on opening line can cause indentation error else if ( tokens.opening.line is tokens.lastProp.firstLine and requested is 'props-aligned' ) 'line-aligned' # Else use configuration dependent on selfClosing property else requested ###* # Get the correct 0-indexed column for the closing bracket, given the # expected location. # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @return {?Number} The correct column for the closing bracket, or null ### getCorrectColumn = (tokens, expectedLocation) -> switch expectedLocation when 'props-aligned' return tokens.lastProp.column when 'tag-aligned' return tokens.opening.column when 'line-aligned' return tokens.openingStartOfLine.column else return null ###* # Check if the closing bracket is correctly located # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @return {Boolean} True if the closing bracket is correctly located, false if not ### hasCorrectLocation = (tokens, expectedLocation) -> switch expectedLocation when 'after-tag' return tokens.tag.line is tokens.closing.line when 'after-props' return tokens.lastProp.lastLine is tokens.closing.line when 'props-aligned', 'tag-aligned', 'line-aligned' correctColumn = getCorrectColumn tokens, expectedLocation return correctColumn is tokens.closing.column else return yes ###* # Get the characters used for indentation on the line to be matched # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @param {Number} correctColumn Expected column for the closing bracket # @return {String} The characters used for indentation ### getIndentation = (tokens, expectedLocation, correctColumn) -> spaces = [] switch expectedLocation when 'props-aligned' indentation = /^\s*/.exec(sourceCode.lines[tokens.lastProp.firstLine - 1])[0] when 'tag-aligned', 'line-aligned' indentation = /^\s*/.exec(sourceCode.lines[tokens.opening.line - 1])[0] else indentation = '' if indentation.length + 1 < correctColumn # Non-whitespace characters were included in the column offset spaces = new Array +correctColumn + 1 - indentation.length indentation + spaces.join ' ' ###* # Get the locations of the opening bracket, closing bracket, last prop, and # start of opening line. # @param {ASTNode} node The node to check # @return {Object} Locations of the opening bracket, closing bracket, last # prop and start of opening line. ### getTokensLocations = (node) -> opening = sourceCode.getFirstToken(node).loc.start closing = sourceCode.getLastTokens(node, if node.selfClosing then 2 else 1)[0].loc .start tag = sourceCode.getFirstToken(node.name).loc.start if node.attributes.length lastProp = node.attributes[node.attributes.length - 1] lastProp = column: sourceCode.getFirstToken(lastProp).loc.start.column firstLine: sourceCode.getFirstToken(lastProp).loc.start.line lastLine: sourceCode.getLastToken(lastProp).loc.end.line openingLine = sourceCode.lines[opening.line - 1] openingStartOfLine = column: /^\s*/.exec(openingLine)[0].length line: opening.line { tag opening closing lastProp selfClosing: node.selfClosing openingStartOfLine } ###* # Get an unique ID for a given JSXOpeningElement # # @param {ASTNode} node The AST node being checked. # @returns {String} Unique ID (based on its range) ### getOpeningElementId = (node) -> node.range.join ':' lastAttributeNode = {} JSXAttribute: (node) -> lastAttributeNode[getOpeningElementId node.parent] = node JSXSpreadAttribute: (node) -> lastAttributeNode[getOpeningElementId node.parent] = node 'JSXOpeningElement:exit': (node) -> attributeNode = lastAttributeNode[getOpeningElementId node] cachedLastAttributeEndPos = if attributeNode attributeNode.range[1] else null tokens = getTokensLocations node expectedLocation = getExpectedLocation tokens return if hasCorrectLocation tokens, expectedLocation data = location: MESSAGE_LOCATION[expectedLocation], details: '' correctColumn = getCorrectColumn tokens, expectedLocation unless correctColumn is null expectedNextLine = tokens.lastProp and tokens.lastProp.lastLine is tokens.closing.line data.details = " (expected column #{correctColumn + 1}#{ if expectedNextLine then ' on the next line)' else ')' }" context.report { node loc: tokens.closing message: MESSAGE data fix: (fixer) -> closingTag = if tokens.selfClosing then '/>' else '>' switch expectedLocation when 'after-tag' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] (if expectedNextLine then '\n' else '') + closingTag ) if cachedLastAttributeEndPos return fixer.replaceTextRange( [node.name.range[1], node.range[1]] (if expectedNextLine then '\n' else ' ') + closingTag ) when 'after-props' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] (if expectedNextLine then '\n' else '') + closingTag ) when 'props-aligned', 'tag-aligned', 'line-aligned' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] "\n#{getIndentation( tokens expectedLocation correctColumn )}#{closingTag}" ) else return yes }
true
###* # @fileoverview Validate closing bracket location in JSX # @author PI:NAME:<NAME>END_PI ### 'use strict' {has} = require 'lodash' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Validate closing bracket location in JSX' category: 'Stylistic Issues' recommended: no url: docsUrl 'jsx-closing-bracket-location' fixable: 'code' schema: [ oneOf: [ enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' ] , type: 'object' properties: location: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' ] additionalProperties: no , type: 'object' properties: nonEmpty: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' no ] selfClosing: enum: [ 'after-props' 'props-aligned' # 'tag-aligned' 'line-aligned' no ] additionalProperties: no ] ] create: (context) -> MESSAGE = 'The closing bracket must be {{location}}{{details}}' MESSAGE_LOCATION = 'after-props': 'placed after the last prop' 'after-tag': 'placed after the opening tag' 'props-aligned': 'aligned with the last prop' # 'tag-aligned': 'aligned with the opening tag' 'line-aligned': 'aligned with the line containing the opening tag' DEFAULT_LOCATION = 'line-aligned' sourceCode = context.getSourceCode() config = context.options[0] options = nonEmpty: DEFAULT_LOCATION selfClosing: DEFAULT_LOCATION if typeof config is 'string' # simple shorthand [1, 'something'] options.nonEmpty = config options.selfClosing = config else if typeof config is 'object' # [1, {location: 'something'}] (back-compat) if has config, 'location' options.nonEmpty = config.location options.selfClosing = config.location # [1, {nonEmpty: 'something'}] if has config, 'nonEmpty' then options.nonEmpty = config.nonEmpty # [1, {selfClosing: 'something'}] if has config, 'selfClosing' then options.selfClosing = config.selfClosing ###* # Get expected location for the closing bracket # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @return {String} Expected location for the closing bracket ### getExpectedLocation = (tokens) -> requested = if tokens.selfClosing options.selfClosing else options.nonEmpty # Is always after the opening tag if there is no props unless tokens.lastProp? 'after-tag' # Is always after the last prop if this one is on the same line as the opening bracket else if tokens.opening.line is tokens.lastProp.lastLine 'after-props' # Aligning with prop that's on opening line can cause indentation error else if ( tokens.opening.line is tokens.lastProp.firstLine and requested is 'props-aligned' ) 'line-aligned' # Else use configuration dependent on selfClosing property else requested ###* # Get the correct 0-indexed column for the closing bracket, given the # expected location. # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @return {?Number} The correct column for the closing bracket, or null ### getCorrectColumn = (tokens, expectedLocation) -> switch expectedLocation when 'props-aligned' return tokens.lastProp.column when 'tag-aligned' return tokens.opening.column when 'line-aligned' return tokens.openingStartOfLine.column else return null ###* # Check if the closing bracket is correctly located # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @return {Boolean} True if the closing bracket is correctly located, false if not ### hasCorrectLocation = (tokens, expectedLocation) -> switch expectedLocation when 'after-tag' return tokens.tag.line is tokens.closing.line when 'after-props' return tokens.lastProp.lastLine is tokens.closing.line when 'props-aligned', 'tag-aligned', 'line-aligned' correctColumn = getCorrectColumn tokens, expectedLocation return correctColumn is tokens.closing.column else return yes ###* # Get the characters used for indentation on the line to be matched # @param {Object} tokens Locations of the opening bracket, closing bracket and last prop # @param {String} expectedLocation Expected location for the closing bracket # @param {Number} correctColumn Expected column for the closing bracket # @return {String} The characters used for indentation ### getIndentation = (tokens, expectedLocation, correctColumn) -> spaces = [] switch expectedLocation when 'props-aligned' indentation = /^\s*/.exec(sourceCode.lines[tokens.lastProp.firstLine - 1])[0] when 'tag-aligned', 'line-aligned' indentation = /^\s*/.exec(sourceCode.lines[tokens.opening.line - 1])[0] else indentation = '' if indentation.length + 1 < correctColumn # Non-whitespace characters were included in the column offset spaces = new Array +correctColumn + 1 - indentation.length indentation + spaces.join ' ' ###* # Get the locations of the opening bracket, closing bracket, last prop, and # start of opening line. # @param {ASTNode} node The node to check # @return {Object} Locations of the opening bracket, closing bracket, last # prop and start of opening line. ### getTokensLocations = (node) -> opening = sourceCode.getFirstToken(node).loc.start closing = sourceCode.getLastTokens(node, if node.selfClosing then 2 else 1)[0].loc .start tag = sourceCode.getFirstToken(node.name).loc.start if node.attributes.length lastProp = node.attributes[node.attributes.length - 1] lastProp = column: sourceCode.getFirstToken(lastProp).loc.start.column firstLine: sourceCode.getFirstToken(lastProp).loc.start.line lastLine: sourceCode.getLastToken(lastProp).loc.end.line openingLine = sourceCode.lines[opening.line - 1] openingStartOfLine = column: /^\s*/.exec(openingLine)[0].length line: opening.line { tag opening closing lastProp selfClosing: node.selfClosing openingStartOfLine } ###* # Get an unique ID for a given JSXOpeningElement # # @param {ASTNode} node The AST node being checked. # @returns {String} Unique ID (based on its range) ### getOpeningElementId = (node) -> node.range.join ':' lastAttributeNode = {} JSXAttribute: (node) -> lastAttributeNode[getOpeningElementId node.parent] = node JSXSpreadAttribute: (node) -> lastAttributeNode[getOpeningElementId node.parent] = node 'JSXOpeningElement:exit': (node) -> attributeNode = lastAttributeNode[getOpeningElementId node] cachedLastAttributeEndPos = if attributeNode attributeNode.range[1] else null tokens = getTokensLocations node expectedLocation = getExpectedLocation tokens return if hasCorrectLocation tokens, expectedLocation data = location: MESSAGE_LOCATION[expectedLocation], details: '' correctColumn = getCorrectColumn tokens, expectedLocation unless correctColumn is null expectedNextLine = tokens.lastProp and tokens.lastProp.lastLine is tokens.closing.line data.details = " (expected column #{correctColumn + 1}#{ if expectedNextLine then ' on the next line)' else ')' }" context.report { node loc: tokens.closing message: MESSAGE data fix: (fixer) -> closingTag = if tokens.selfClosing then '/>' else '>' switch expectedLocation when 'after-tag' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] (if expectedNextLine then '\n' else '') + closingTag ) if cachedLastAttributeEndPos return fixer.replaceTextRange( [node.name.range[1], node.range[1]] (if expectedNextLine then '\n' else ' ') + closingTag ) when 'after-props' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] (if expectedNextLine then '\n' else '') + closingTag ) when 'props-aligned', 'tag-aligned', 'line-aligned' return fixer.replaceTextRange( [cachedLastAttributeEndPos, node.range[1]] "\n#{getIndentation( tokens expectedLocation correctColumn )}#{closingTag}" ) else return yes }
[ { "context": "req =\n params: {}\n body:\n name: 'test1'\n description: 'My awesome pipeline'\n ", "end": 198, "score": 0.8273487687110901, "start": 193, "tag": "NAME", "value": "test1" }, { "context": "me is already used', (done)->\n item = name: 'test1'\n p = Pipeline(pipelines: [item])\n @req", "end": 684, "score": 0.869886040687561, "start": 679, "tag": "NAME", "value": "test1" }, { "context": "ine(pipelines: [item])\n @req.body = { name: 'test1' }\n p.validate @req, @res, (err)->\n s", "end": 756, "score": 0.9148932695388794, "start": 751, "tag": "NAME", "value": "test1" }, { "context": "@req.params.id = 123\n item = id: 123, name: 'test1'\n p = Pipeline(pipelines: [item])\n p.fi", "end": 3655, "score": 0.9512113928794861, "start": 3650, "tag": "NAME", "value": "test1" }, { "context": "req.params.id = 123\n @item = id: 123, name: 'test1'\n @list = [@item]\n @p = Pipeline(pipeli", "end": 4165, "score": 0.9693107008934021, "start": 4160, "tag": "NAME", "value": "test1" }, { "context": "f all pipelines', (done)->\n list = [{ name: 'test1'}, { name: 'test2' }]\n p = Pipeline(pipeline", "end": 4924, "score": 0.9065643548965454, "start": 4919, "tag": "NAME", "value": "test1" }, { "context": "(done)->\n list = [{ name: 'test1'}, { name: 'test2' }]\n p = Pipeline(pipelines: list)\n p.a", "end": 4942, "score": 0.8788940906524658, "start": 4937, "tag": "NAME", "value": "test2" } ]
test/pipeline.coffee
kr1sp1n/service-pipeline
1
should = require 'should' describe 'Pipeline', -> Pipeline = require "#{__dirname}/../src/pipeline" beforeEach -> @res = null @req = params: {} body: name: 'test1' description: 'My awesome pipeline' steps: [ { template: { uri: "https://example.com/mytemplate" } } ] globals: hello: 'World' callbacks: success: { uri: "https://example.com/success" } describe 'validate', -> it 'should pass if req.body is valid', (done)-> p = Pipeline() p.validate @req, @res, (err)=> done err it 'should throw an error if name is already used', (done)-> item = name: 'test1' p = Pipeline(pipelines: [item]) @req.body = { name: 'test1' } p.validate @req, @res, (err)-> should.exist(err) err.message.should.equal "Pipeline with name #{item.name} already exists" done null it 'should throw an error if name is empty', (done)-> p = Pipeline() @req.body = {} p.validate @req, @res, (err)-> should.exist(err) err.message.should.equal "Pipeline with no name is not allowed" done null describe 'newItem', -> beforeEach -> @p = Pipeline() it 'should extend req with a new pipeline', (done)-> @p.newItem @req, @res, (err)=> @req.should.have.property 'pipeline' @req.pipeline.name.should.equal @req.body.name @req.pipeline.description.should.equal @req.body.description @req.pipeline.steps.should.equal @req.body.steps @req.pipeline.globals.should.equal @req.body.globals @req.pipeline.callbacks.should.equal @req.body.callbacks done err it 'should generate a unique id if no req.body.id', (done)-> @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'id' done err it 'should overwrite unique id if req.body.id', (done)-> @req.body.id = '123' @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'id', @req.body.id done err it 'should set description to empty string if no req.body.description', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'description', '' done err it 'should set steps to empty array if no req.body.steps', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'steps', [] done err it 'should set globals to empty object if no req.body.globals', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'globals', {} done err it 'should set callbacks to empty object if no req.body.callbacks', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'callbacks', {} done err describe 'add', -> it 'should save a new pipeline into a list', (done)-> list = [] @req.pipeline = name: 'test1' p = Pipeline(pipelines: list) p.add @req, @res, (err)=> list.length.should.equal 1 done err describe 'create', -> beforeEach -> @p = Pipeline() it 'should be an array of functions', -> @p.create.should.be.an.array it 'should have the right order of functions', -> @p.create[0].should.eql @p.validate @p.create[1].should.eql @p.newItem @p.create[2].should.eql @p.add describe 'find', -> it 'should find a pipeline by its id', (done)-> @req.params.id = 123 item = id: 123, name: 'test1' p = Pipeline(pipelines: [item]) p.find @req, @res, (err)=> @req.pipeline.should.equal item done err it 'should throw an error if pipeline was not found', (done)-> @req.params.id = 123 p = Pipeline() p.find @req, @res, (err)=> should.exist(err) err.message.should.equal "Pipeline with id #{@req.params.id} not found" done null describe 'remove', -> beforeEach -> @req.params.id = 123 @item = id: 123, name: 'test1' @list = [@item] @p = Pipeline(pipelines: @list) it 'should delete a pipeline from a list', (done)-> @p.remove @req, @res, (err)=> @list.length.should.equal 0 done err it 'should extend req with the removed pipeline', (done)-> @p.remove @req, @res, (err)=> @req.pipeline.should.eql @item done err it 'should throw an error if pipeline could not be found by its id', (done)-> @req.params.id = 'wtf' @p.remove @req, @res, (err)=> should.exist(err) err.message.should.equal "Pipeline with id #{@req.params.id} does not exist" done null describe 'all', -> it 'should extend req with a list of all pipelines', (done)-> list = [{ name: 'test1'}, { name: 'test2' }] p = Pipeline(pipelines: list) p.all @req, @res, (err)=> @req.should.have.property 'pipelines' @req.pipelines.should.eql list done err
68545
should = require 'should' describe 'Pipeline', -> Pipeline = require "#{__dirname}/../src/pipeline" beforeEach -> @res = null @req = params: {} body: name: '<NAME>' description: 'My awesome pipeline' steps: [ { template: { uri: "https://example.com/mytemplate" } } ] globals: hello: 'World' callbacks: success: { uri: "https://example.com/success" } describe 'validate', -> it 'should pass if req.body is valid', (done)-> p = Pipeline() p.validate @req, @res, (err)=> done err it 'should throw an error if name is already used', (done)-> item = name: '<NAME>' p = Pipeline(pipelines: [item]) @req.body = { name: '<NAME>' } p.validate @req, @res, (err)-> should.exist(err) err.message.should.equal "Pipeline with name #{item.name} already exists" done null it 'should throw an error if name is empty', (done)-> p = Pipeline() @req.body = {} p.validate @req, @res, (err)-> should.exist(err) err.message.should.equal "Pipeline with no name is not allowed" done null describe 'newItem', -> beforeEach -> @p = Pipeline() it 'should extend req with a new pipeline', (done)-> @p.newItem @req, @res, (err)=> @req.should.have.property 'pipeline' @req.pipeline.name.should.equal @req.body.name @req.pipeline.description.should.equal @req.body.description @req.pipeline.steps.should.equal @req.body.steps @req.pipeline.globals.should.equal @req.body.globals @req.pipeline.callbacks.should.equal @req.body.callbacks done err it 'should generate a unique id if no req.body.id', (done)-> @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'id' done err it 'should overwrite unique id if req.body.id', (done)-> @req.body.id = '123' @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'id', @req.body.id done err it 'should set description to empty string if no req.body.description', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'description', '' done err it 'should set steps to empty array if no req.body.steps', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'steps', [] done err it 'should set globals to empty object if no req.body.globals', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'globals', {} done err it 'should set callbacks to empty object if no req.body.callbacks', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'callbacks', {} done err describe 'add', -> it 'should save a new pipeline into a list', (done)-> list = [] @req.pipeline = name: 'test1' p = Pipeline(pipelines: list) p.add @req, @res, (err)=> list.length.should.equal 1 done err describe 'create', -> beforeEach -> @p = Pipeline() it 'should be an array of functions', -> @p.create.should.be.an.array it 'should have the right order of functions', -> @p.create[0].should.eql @p.validate @p.create[1].should.eql @p.newItem @p.create[2].should.eql @p.add describe 'find', -> it 'should find a pipeline by its id', (done)-> @req.params.id = 123 item = id: 123, name: '<NAME>' p = Pipeline(pipelines: [item]) p.find @req, @res, (err)=> @req.pipeline.should.equal item done err it 'should throw an error if pipeline was not found', (done)-> @req.params.id = 123 p = Pipeline() p.find @req, @res, (err)=> should.exist(err) err.message.should.equal "Pipeline with id #{@req.params.id} not found" done null describe 'remove', -> beforeEach -> @req.params.id = 123 @item = id: 123, name: '<NAME>' @list = [@item] @p = Pipeline(pipelines: @list) it 'should delete a pipeline from a list', (done)-> @p.remove @req, @res, (err)=> @list.length.should.equal 0 done err it 'should extend req with the removed pipeline', (done)-> @p.remove @req, @res, (err)=> @req.pipeline.should.eql @item done err it 'should throw an error if pipeline could not be found by its id', (done)-> @req.params.id = 'wtf' @p.remove @req, @res, (err)=> should.exist(err) err.message.should.equal "Pipeline with id #{@req.params.id} does not exist" done null describe 'all', -> it 'should extend req with a list of all pipelines', (done)-> list = [{ name: '<NAME>'}, { name: '<NAME>' }] p = Pipeline(pipelines: list) p.all @req, @res, (err)=> @req.should.have.property 'pipelines' @req.pipelines.should.eql list done err
true
should = require 'should' describe 'Pipeline', -> Pipeline = require "#{__dirname}/../src/pipeline" beforeEach -> @res = null @req = params: {} body: name: 'PI:NAME:<NAME>END_PI' description: 'My awesome pipeline' steps: [ { template: { uri: "https://example.com/mytemplate" } } ] globals: hello: 'World' callbacks: success: { uri: "https://example.com/success" } describe 'validate', -> it 'should pass if req.body is valid', (done)-> p = Pipeline() p.validate @req, @res, (err)=> done err it 'should throw an error if name is already used', (done)-> item = name: 'PI:NAME:<NAME>END_PI' p = Pipeline(pipelines: [item]) @req.body = { name: 'PI:NAME:<NAME>END_PI' } p.validate @req, @res, (err)-> should.exist(err) err.message.should.equal "Pipeline with name #{item.name} already exists" done null it 'should throw an error if name is empty', (done)-> p = Pipeline() @req.body = {} p.validate @req, @res, (err)-> should.exist(err) err.message.should.equal "Pipeline with no name is not allowed" done null describe 'newItem', -> beforeEach -> @p = Pipeline() it 'should extend req with a new pipeline', (done)-> @p.newItem @req, @res, (err)=> @req.should.have.property 'pipeline' @req.pipeline.name.should.equal @req.body.name @req.pipeline.description.should.equal @req.body.description @req.pipeline.steps.should.equal @req.body.steps @req.pipeline.globals.should.equal @req.body.globals @req.pipeline.callbacks.should.equal @req.body.callbacks done err it 'should generate a unique id if no req.body.id', (done)-> @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'id' done err it 'should overwrite unique id if req.body.id', (done)-> @req.body.id = '123' @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'id', @req.body.id done err it 'should set description to empty string if no req.body.description', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'description', '' done err it 'should set steps to empty array if no req.body.steps', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'steps', [] done err it 'should set globals to empty object if no req.body.globals', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'globals', {} done err it 'should set callbacks to empty object if no req.body.callbacks', (done)-> @req.body = {} @p.newItem @req, @res, (err)=> @req.pipeline.should.have.property 'callbacks', {} done err describe 'add', -> it 'should save a new pipeline into a list', (done)-> list = [] @req.pipeline = name: 'test1' p = Pipeline(pipelines: list) p.add @req, @res, (err)=> list.length.should.equal 1 done err describe 'create', -> beforeEach -> @p = Pipeline() it 'should be an array of functions', -> @p.create.should.be.an.array it 'should have the right order of functions', -> @p.create[0].should.eql @p.validate @p.create[1].should.eql @p.newItem @p.create[2].should.eql @p.add describe 'find', -> it 'should find a pipeline by its id', (done)-> @req.params.id = 123 item = id: 123, name: 'PI:NAME:<NAME>END_PI' p = Pipeline(pipelines: [item]) p.find @req, @res, (err)=> @req.pipeline.should.equal item done err it 'should throw an error if pipeline was not found', (done)-> @req.params.id = 123 p = Pipeline() p.find @req, @res, (err)=> should.exist(err) err.message.should.equal "Pipeline with id #{@req.params.id} not found" done null describe 'remove', -> beforeEach -> @req.params.id = 123 @item = id: 123, name: 'PI:NAME:<NAME>END_PI' @list = [@item] @p = Pipeline(pipelines: @list) it 'should delete a pipeline from a list', (done)-> @p.remove @req, @res, (err)=> @list.length.should.equal 0 done err it 'should extend req with the removed pipeline', (done)-> @p.remove @req, @res, (err)=> @req.pipeline.should.eql @item done err it 'should throw an error if pipeline could not be found by its id', (done)-> @req.params.id = 'wtf' @p.remove @req, @res, (err)=> should.exist(err) err.message.should.equal "Pipeline with id #{@req.params.id} does not exist" done null describe 'all', -> it 'should extend req with a list of all pipelines', (done)-> list = [{ name: 'PI:NAME:<NAME>END_PI'}, { name: 'PI:NAME:<NAME>END_PI' }] p = Pipeline(pipelines: list) p.all @req, @res, (err)=> @req.should.have.property 'pipelines' @req.pipelines.should.eql list done err
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998900294303894, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhakim RAFIK\n * @date \t\tMar 2021\n###\n\n###\n\tCreate providers ta", "end": 129, "score": 0.9998908042907715, "start": 113, "tag": "NAME", "value": "Abdelhakim RAFIK" } ]
src/database/migrations/2021032400002-create-providers.coffee
AbdelhakimRafik/Pharmalogy-API
0
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Mar 2021 ### ### Create providers table migration ### module.exports = up: (queryInterface, Sequelize) -> queryInterface.createTable 'Providers', id: allowNull: false autoIncrement: true primaryKey: true type: Sequelize.INTEGER name: allowNull: false type: Sequelize.STRING addresse: type: Sequelize.STRING email: type: Sequelize.STRING webSite: type: Sequelize.STRING phone: type: Sequelize.STRING 10 city: allowNull: false, type: Sequelize.STRING country: allowNull: false, type: Sequelize.STRING status: allowNull: false type: Sequelize.BOOLEAN defaultValue: false createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE down: (queryInterface, Sequelize) -> queryInterface.dropTable 'Providers'
158063
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date Mar 2021 ### ### Create providers table migration ### module.exports = up: (queryInterface, Sequelize) -> queryInterface.createTable 'Providers', id: allowNull: false autoIncrement: true primaryKey: true type: Sequelize.INTEGER name: allowNull: false type: Sequelize.STRING addresse: type: Sequelize.STRING email: type: Sequelize.STRING webSite: type: Sequelize.STRING phone: type: Sequelize.STRING 10 city: allowNull: false, type: Sequelize.STRING country: allowNull: false, type: Sequelize.STRING status: allowNull: false type: Sequelize.BOOLEAN defaultValue: false createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE down: (queryInterface, Sequelize) -> queryInterface.dropTable 'Providers'
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date Mar 2021 ### ### Create providers table migration ### module.exports = up: (queryInterface, Sequelize) -> queryInterface.createTable 'Providers', id: allowNull: false autoIncrement: true primaryKey: true type: Sequelize.INTEGER name: allowNull: false type: Sequelize.STRING addresse: type: Sequelize.STRING email: type: Sequelize.STRING webSite: type: Sequelize.STRING phone: type: Sequelize.STRING 10 city: allowNull: false, type: Sequelize.STRING country: allowNull: false, type: Sequelize.STRING status: allowNull: false type: Sequelize.BOOLEAN defaultValue: false createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE down: (queryInterface, Sequelize) -> queryInterface.dropTable 'Providers'
[ { "context": "ld ($a) ->\n expect($a).to.contain(@user.name)\n\n it \"displays username in success", "end": 2621, "score": 0.6203030347824097, "start": 2617, "tag": "USERNAME", "value": "user" }, { "context": "ialog\", ->\n cy.get(\".modal\").contains(\"Jane Lane\")\n\n it \"can close modal by clicking Cont", "end": 2732, "score": 0.9990825653076172, "start": 2723, "tag": "NAME", "value": "Jane Lane" }, { "context": " cy\n .get(\"nav a\").contains(\"Jane\").click()\n cy\n .c", "end": 3223, "score": 0.981580376625061, "start": 3219, "tag": "NAME", "value": "Jane" }, { "context": " cy\n .get(\"nav a\").contains(\"Jane\").click()\n cy\n .c", "end": 3466, "score": 0.9436174631118774, "start": 3462, "tag": "NAME", "value": "Jane" }, { "context": " cy\n .get(\"nav a\").contains(\"Jane\").click()\n cy\n .c", "end": 3719, "score": 0.9745683670043945, "start": 3715, "tag": "NAME", "value": "Jane" }, { "context": "ut\", ->\n cy.get(\"nav a\").contains(\"Jane\").click()\n cy.contains(\"Log Out\").", "end": 3989, "score": 0.9752541184425354, "start": 3985, "tag": "NAME", "value": "Jane" } ]
packages/desktop-gui/cypress/integration/login_spec.coffee
zacharoth/cypress
0
describe "Login", -> beforeEach -> cy.fixture("user").as("user") cy.visitIndex().then (win) -> { start, @ipc } = win.App cy.stub(@ipc, "onMenuClicked") cy.stub(@ipc, "getOptions").resolves({}) cy.stub(@ipc, "getCurrentUser").resolves(null) cy.stub(@ipc, "updaterCheck").resolves(false) cy.stub(@ipc, "getProjects").resolves([]) cy.stub(@ipc, "getProjectStatuses").resolves([]) cy.stub(@ipc, "openProject").resolves(@config) cy.stub(@ipc, "getSpecs").yields(null, @specs) cy.stub(@ipc, "externalOpen") cy.stub(@ipc, "clearGithubCookies") cy.stub(@ipc, "logOut").resolves() cy.stub(@ipc, "onAuthMessage").callsFake (cb) => @onAuthMessageCb = cb @pingApiServer = @util.deferred() cy.stub(@ipc, "pingApiServer").returns(@pingApiServer.promise) @beginAuth = @util.deferred() cy.stub(@ipc, "beginAuth").returns(@beginAuth.promise) start() cy.contains("Log In").click() it "pings api server", -> expect(@ipc.pingApiServer).to.be.called cy.get(".loader") describe "when connected to api server", -> beforeEach -> @pingApiServer.resolve() it "has dashboard login button", -> cy.get(".login").contains("button", "Log In to Dashboard") it "opens dashboard on clicking 'Cypress Dashboard'", -> cy.contains("Cypress Dashboard").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard") describe "click 'Log In to Dashboard'", -> beforeEach -> cy .get(".login") .contains("button", "Log In to Dashboard").as("loginBtn") .click() it "triggers ipc 'begin:auth' on click", -> cy .then -> expect(@ipc.beginAuth).to.be.calledOnce it "disables login button", -> cy.get("@loginBtn").should("be.disabled") it "shows spinner with 'Opening browser'", -> cy.get("@loginBtn").invoke("text").should("contain", "Opening browser...") context "on 'begin:auth'", -> beforeEach -> cy.get("@loginBtn") it "displays spinner with 'Opening browser...' and disables button", -> cy.contains("Opening browser...").should("be.disabled") describe "on ipc begin:auth success", -> beforeEach -> @beginAuth.resolve(@user) it "goes to previous view", -> cy.shouldBeOnIntro() it "displays username in UI", -> cy .get("nav a").should ($a) -> expect($a).to.contain(@user.name) it "displays username in success dialog", -> cy.get(".modal").contains("Jane Lane") it "can close modal by clicking Continue", -> cy.get(".modal .btn:contains(Continue)").click() .then -> cy.get(".modal").should("not.be.visible") context "after clicking Continue", -> beforeEach -> cy.get(".modal .btn:contains(Continue)").click() context "log out", -> it "displays login button on logout", -> cy .get("nav a").contains("Jane").click() cy .contains("Log Out").click() .get(".nav").contains("Log In") it "calls clear:github:cookies", -> cy .get("nav a").contains("Jane").click() cy .contains("Log Out").click().then -> expect(@ipc.clearGithubCookies).to.be.called it "calls log:out", -> cy .get("nav a").contains("Jane").click() cy .contains("Log Out").click().then -> expect(@ipc.logOut).to.be.called it "has login button enabled when returning to login after logout", -> cy.get("nav a").contains("Jane").click() cy.contains("Log Out").click() cy.contains("Log In").click() cy.get(".login button").eq(1) .should("not.be.disabled") .invoke("text") .should("include", "Log In to Dashboard") describe "on ipc 'begin:auth' error", -> beforeEach -> @beginAuth.reject({name: "foo", message: "There's an error"}) it "displays error in ui", -> cy .get(".alert-danger") .should("be.visible") .contains("There's an error") it "login button should be enabled", -> cy .get("@loginBtn").should("not.be.disabled") describe "on ipc 'on:auth:message'", -> beforeEach -> @onAuthMessageCb(null, { message: "some warning here" type: "warning" }) it "displays warning in ui", -> cy .get(".warning") .should("be.visible") .contains("some warning here") it "login button should be disabled", -> cy .get("@loginBtn").should("be.disabled") it "on AUTH_COULD_NOT_LAUNCH_BROWSER login button changes", -> @onAuthMessageCb(null, { name: "AUTH_COULD_NOT_LAUNCH_BROWSER" type: "warning" message: "foo" }) cy .get(".login-content .btn-login") .should("be.disabled") .should("have.text", " Could not open browser.") it "<pre> can be click-selected", -> @onAuthMessageCb(null, { message: """ foo ``` bar ``` """ type: "warning" }) cy .get(".login-content .message pre") .click() .document() .then ($doc) -> expect($doc.getSelection().toString()).to.eq('bar') describe "Dashboard link in message", -> it "opens link to Dashboard Service on click", -> cy.contains("a", "Cypress Dashboard Service").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard") describe "terms and privacy message", -> it "opens links to terms and privacy on click", -> cy.contains("a", "Terms of Use").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/terms-of-use") cy.contains("a", "Privacy Policy").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/privacy-policy") describe "when not connected to api server", -> beforeEach -> @pingApiServerAgain = @util.deferred() @ipc.pingApiServer.onCall(1).returns(@pingApiServerAgain.promise) @pingApiServer.reject({ apiUrl: "http://api.server" message: "ECONNREFUSED" }) it "shows 'cannot connect to api server' message", -> cy.contains("Cannot connect to API server") cy.contains("http://api.server") cy.contains("ECONNREFUSED") describe "trying again", -> beforeEach -> cy.contains("Try again").click() it "pings again", -> cy.get(".loader").then -> expect(@ipc.pingApiServer).to.be.calledTwice it "shows new error on failure", -> @pingApiServerAgain.reject({ apiUrl: "http://api.server" message: "WHADJAEXPECT" }) cy.contains("Cannot connect to API server") cy.contains("http://api.server") cy.contains("WHADJAEXPECT") it "shows login on success", -> @pingApiServerAgain.resolve() cy.get(".login").contains("button", "Log In to Dashboard") describe "api help link", -> it "goes to external api help link", -> cy.contains("Learn more").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/help-connect-to-api") describe "closing login", -> beforeEach -> cy.get(".login .close").click() it "shows log in if connected and opened again", -> @pingApiServerAgain.resolve() cy.contains("Log In").click() cy.get(".login").contains("button", "Log In to Dashboard")
164967
describe "Login", -> beforeEach -> cy.fixture("user").as("user") cy.visitIndex().then (win) -> { start, @ipc } = win.App cy.stub(@ipc, "onMenuClicked") cy.stub(@ipc, "getOptions").resolves({}) cy.stub(@ipc, "getCurrentUser").resolves(null) cy.stub(@ipc, "updaterCheck").resolves(false) cy.stub(@ipc, "getProjects").resolves([]) cy.stub(@ipc, "getProjectStatuses").resolves([]) cy.stub(@ipc, "openProject").resolves(@config) cy.stub(@ipc, "getSpecs").yields(null, @specs) cy.stub(@ipc, "externalOpen") cy.stub(@ipc, "clearGithubCookies") cy.stub(@ipc, "logOut").resolves() cy.stub(@ipc, "onAuthMessage").callsFake (cb) => @onAuthMessageCb = cb @pingApiServer = @util.deferred() cy.stub(@ipc, "pingApiServer").returns(@pingApiServer.promise) @beginAuth = @util.deferred() cy.stub(@ipc, "beginAuth").returns(@beginAuth.promise) start() cy.contains("Log In").click() it "pings api server", -> expect(@ipc.pingApiServer).to.be.called cy.get(".loader") describe "when connected to api server", -> beforeEach -> @pingApiServer.resolve() it "has dashboard login button", -> cy.get(".login").contains("button", "Log In to Dashboard") it "opens dashboard on clicking 'Cypress Dashboard'", -> cy.contains("Cypress Dashboard").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard") describe "click 'Log In to Dashboard'", -> beforeEach -> cy .get(".login") .contains("button", "Log In to Dashboard").as("loginBtn") .click() it "triggers ipc 'begin:auth' on click", -> cy .then -> expect(@ipc.beginAuth).to.be.calledOnce it "disables login button", -> cy.get("@loginBtn").should("be.disabled") it "shows spinner with 'Opening browser'", -> cy.get("@loginBtn").invoke("text").should("contain", "Opening browser...") context "on 'begin:auth'", -> beforeEach -> cy.get("@loginBtn") it "displays spinner with 'Opening browser...' and disables button", -> cy.contains("Opening browser...").should("be.disabled") describe "on ipc begin:auth success", -> beforeEach -> @beginAuth.resolve(@user) it "goes to previous view", -> cy.shouldBeOnIntro() it "displays username in UI", -> cy .get("nav a").should ($a) -> expect($a).to.contain(@user.name) it "displays username in success dialog", -> cy.get(".modal").contains("<NAME>") it "can close modal by clicking Continue", -> cy.get(".modal .btn:contains(Continue)").click() .then -> cy.get(".modal").should("not.be.visible") context "after clicking Continue", -> beforeEach -> cy.get(".modal .btn:contains(Continue)").click() context "log out", -> it "displays login button on logout", -> cy .get("nav a").contains("<NAME>").click() cy .contains("Log Out").click() .get(".nav").contains("Log In") it "calls clear:github:cookies", -> cy .get("nav a").contains("<NAME>").click() cy .contains("Log Out").click().then -> expect(@ipc.clearGithubCookies).to.be.called it "calls log:out", -> cy .get("nav a").contains("<NAME>").click() cy .contains("Log Out").click().then -> expect(@ipc.logOut).to.be.called it "has login button enabled when returning to login after logout", -> cy.get("nav a").contains("<NAME>").click() cy.contains("Log Out").click() cy.contains("Log In").click() cy.get(".login button").eq(1) .should("not.be.disabled") .invoke("text") .should("include", "Log In to Dashboard") describe "on ipc 'begin:auth' error", -> beforeEach -> @beginAuth.reject({name: "foo", message: "There's an error"}) it "displays error in ui", -> cy .get(".alert-danger") .should("be.visible") .contains("There's an error") it "login button should be enabled", -> cy .get("@loginBtn").should("not.be.disabled") describe "on ipc 'on:auth:message'", -> beforeEach -> @onAuthMessageCb(null, { message: "some warning here" type: "warning" }) it "displays warning in ui", -> cy .get(".warning") .should("be.visible") .contains("some warning here") it "login button should be disabled", -> cy .get("@loginBtn").should("be.disabled") it "on AUTH_COULD_NOT_LAUNCH_BROWSER login button changes", -> @onAuthMessageCb(null, { name: "AUTH_COULD_NOT_LAUNCH_BROWSER" type: "warning" message: "foo" }) cy .get(".login-content .btn-login") .should("be.disabled") .should("have.text", " Could not open browser.") it "<pre> can be click-selected", -> @onAuthMessageCb(null, { message: """ foo ``` bar ``` """ type: "warning" }) cy .get(".login-content .message pre") .click() .document() .then ($doc) -> expect($doc.getSelection().toString()).to.eq('bar') describe "Dashboard link in message", -> it "opens link to Dashboard Service on click", -> cy.contains("a", "Cypress Dashboard Service").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard") describe "terms and privacy message", -> it "opens links to terms and privacy on click", -> cy.contains("a", "Terms of Use").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/terms-of-use") cy.contains("a", "Privacy Policy").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/privacy-policy") describe "when not connected to api server", -> beforeEach -> @pingApiServerAgain = @util.deferred() @ipc.pingApiServer.onCall(1).returns(@pingApiServerAgain.promise) @pingApiServer.reject({ apiUrl: "http://api.server" message: "ECONNREFUSED" }) it "shows 'cannot connect to api server' message", -> cy.contains("Cannot connect to API server") cy.contains("http://api.server") cy.contains("ECONNREFUSED") describe "trying again", -> beforeEach -> cy.contains("Try again").click() it "pings again", -> cy.get(".loader").then -> expect(@ipc.pingApiServer).to.be.calledTwice it "shows new error on failure", -> @pingApiServerAgain.reject({ apiUrl: "http://api.server" message: "WHADJAEXPECT" }) cy.contains("Cannot connect to API server") cy.contains("http://api.server") cy.contains("WHADJAEXPECT") it "shows login on success", -> @pingApiServerAgain.resolve() cy.get(".login").contains("button", "Log In to Dashboard") describe "api help link", -> it "goes to external api help link", -> cy.contains("Learn more").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/help-connect-to-api") describe "closing login", -> beforeEach -> cy.get(".login .close").click() it "shows log in if connected and opened again", -> @pingApiServerAgain.resolve() cy.contains("Log In").click() cy.get(".login").contains("button", "Log In to Dashboard")
true
describe "Login", -> beforeEach -> cy.fixture("user").as("user") cy.visitIndex().then (win) -> { start, @ipc } = win.App cy.stub(@ipc, "onMenuClicked") cy.stub(@ipc, "getOptions").resolves({}) cy.stub(@ipc, "getCurrentUser").resolves(null) cy.stub(@ipc, "updaterCheck").resolves(false) cy.stub(@ipc, "getProjects").resolves([]) cy.stub(@ipc, "getProjectStatuses").resolves([]) cy.stub(@ipc, "openProject").resolves(@config) cy.stub(@ipc, "getSpecs").yields(null, @specs) cy.stub(@ipc, "externalOpen") cy.stub(@ipc, "clearGithubCookies") cy.stub(@ipc, "logOut").resolves() cy.stub(@ipc, "onAuthMessage").callsFake (cb) => @onAuthMessageCb = cb @pingApiServer = @util.deferred() cy.stub(@ipc, "pingApiServer").returns(@pingApiServer.promise) @beginAuth = @util.deferred() cy.stub(@ipc, "beginAuth").returns(@beginAuth.promise) start() cy.contains("Log In").click() it "pings api server", -> expect(@ipc.pingApiServer).to.be.called cy.get(".loader") describe "when connected to api server", -> beforeEach -> @pingApiServer.resolve() it "has dashboard login button", -> cy.get(".login").contains("button", "Log In to Dashboard") it "opens dashboard on clicking 'Cypress Dashboard'", -> cy.contains("Cypress Dashboard").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard") describe "click 'Log In to Dashboard'", -> beforeEach -> cy .get(".login") .contains("button", "Log In to Dashboard").as("loginBtn") .click() it "triggers ipc 'begin:auth' on click", -> cy .then -> expect(@ipc.beginAuth).to.be.calledOnce it "disables login button", -> cy.get("@loginBtn").should("be.disabled") it "shows spinner with 'Opening browser'", -> cy.get("@loginBtn").invoke("text").should("contain", "Opening browser...") context "on 'begin:auth'", -> beforeEach -> cy.get("@loginBtn") it "displays spinner with 'Opening browser...' and disables button", -> cy.contains("Opening browser...").should("be.disabled") describe "on ipc begin:auth success", -> beforeEach -> @beginAuth.resolve(@user) it "goes to previous view", -> cy.shouldBeOnIntro() it "displays username in UI", -> cy .get("nav a").should ($a) -> expect($a).to.contain(@user.name) it "displays username in success dialog", -> cy.get(".modal").contains("PI:NAME:<NAME>END_PI") it "can close modal by clicking Continue", -> cy.get(".modal .btn:contains(Continue)").click() .then -> cy.get(".modal").should("not.be.visible") context "after clicking Continue", -> beforeEach -> cy.get(".modal .btn:contains(Continue)").click() context "log out", -> it "displays login button on logout", -> cy .get("nav a").contains("PI:NAME:<NAME>END_PI").click() cy .contains("Log Out").click() .get(".nav").contains("Log In") it "calls clear:github:cookies", -> cy .get("nav a").contains("PI:NAME:<NAME>END_PI").click() cy .contains("Log Out").click().then -> expect(@ipc.clearGithubCookies).to.be.called it "calls log:out", -> cy .get("nav a").contains("PI:NAME:<NAME>END_PI").click() cy .contains("Log Out").click().then -> expect(@ipc.logOut).to.be.called it "has login button enabled when returning to login after logout", -> cy.get("nav a").contains("PI:NAME:<NAME>END_PI").click() cy.contains("Log Out").click() cy.contains("Log In").click() cy.get(".login button").eq(1) .should("not.be.disabled") .invoke("text") .should("include", "Log In to Dashboard") describe "on ipc 'begin:auth' error", -> beforeEach -> @beginAuth.reject({name: "foo", message: "There's an error"}) it "displays error in ui", -> cy .get(".alert-danger") .should("be.visible") .contains("There's an error") it "login button should be enabled", -> cy .get("@loginBtn").should("not.be.disabled") describe "on ipc 'on:auth:message'", -> beforeEach -> @onAuthMessageCb(null, { message: "some warning here" type: "warning" }) it "displays warning in ui", -> cy .get(".warning") .should("be.visible") .contains("some warning here") it "login button should be disabled", -> cy .get("@loginBtn").should("be.disabled") it "on AUTH_COULD_NOT_LAUNCH_BROWSER login button changes", -> @onAuthMessageCb(null, { name: "AUTH_COULD_NOT_LAUNCH_BROWSER" type: "warning" message: "foo" }) cy .get(".login-content .btn-login") .should("be.disabled") .should("have.text", " Could not open browser.") it "<pre> can be click-selected", -> @onAuthMessageCb(null, { message: """ foo ``` bar ``` """ type: "warning" }) cy .get(".login-content .message pre") .click() .document() .then ($doc) -> expect($doc.getSelection().toString()).to.eq('bar') describe "Dashboard link in message", -> it "opens link to Dashboard Service on click", -> cy.contains("a", "Cypress Dashboard Service").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard") describe "terms and privacy message", -> it "opens links to terms and privacy on click", -> cy.contains("a", "Terms of Use").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/terms-of-use") cy.contains("a", "Privacy Policy").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/privacy-policy") describe "when not connected to api server", -> beforeEach -> @pingApiServerAgain = @util.deferred() @ipc.pingApiServer.onCall(1).returns(@pingApiServerAgain.promise) @pingApiServer.reject({ apiUrl: "http://api.server" message: "ECONNREFUSED" }) it "shows 'cannot connect to api server' message", -> cy.contains("Cannot connect to API server") cy.contains("http://api.server") cy.contains("ECONNREFUSED") describe "trying again", -> beforeEach -> cy.contains("Try again").click() it "pings again", -> cy.get(".loader").then -> expect(@ipc.pingApiServer).to.be.calledTwice it "shows new error on failure", -> @pingApiServerAgain.reject({ apiUrl: "http://api.server" message: "WHADJAEXPECT" }) cy.contains("Cannot connect to API server") cy.contains("http://api.server") cy.contains("WHADJAEXPECT") it "shows login on success", -> @pingApiServerAgain.resolve() cy.get(".login").contains("button", "Log In to Dashboard") describe "api help link", -> it "goes to external api help link", -> cy.contains("Learn more").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/help-connect-to-api") describe "closing login", -> beforeEach -> cy.get(".login .close").click() it "shows log in if connected and opened again", -> @pingApiServerAgain.resolve() cy.contains("Log In").click() cy.get(".login").contains("button", "Log In to Dashboard")
[ { "context": "name\n\t\t\t\t\t\t\temail: req.body.email\n\t\t\t\t\t\t\tpassword: req.body.password\n\t\t\t\t\t\t.then ()->\n\t\t\t\t\t\t\tconsole.log 'ACCOUNT CREA", "end": 716, "score": 0.9992383718490601, "start": 699, "tag": "PASSWORD", "value": "req.body.password" }, { "context": "ckLogin \n\t\t\t\t\temail: req.body.email\n\t\t\t\t\tpassword: req.body.password\n\t\t\t\t.then (result)->\n\t\t\t\t\treq.session.user = resu", "end": 1560, "score": 0.9772924184799194, "start": 1543, "tag": "PASSWORD", "value": "req.body.password" } ]
app/controllers/public.coffee
jrdbnntt/theMenu
0
module.exports = (app) -> class app.PublicController @index = (req, res) -> res.render 'index', title: 'Home' ######################################################################## # Sign up '/signup' @signup = (req, res)-> res.render 'public/signup', title: 'Signup' @signup_submit = (req, res)-> if req.body.username? && req.body.email? && req.body.password? app.models.Account.checkUsernameUnused req.body.username .then ()-> app.models.Account.checkEmailUnused req.body.email .then ()-> # Looks good, create it app.models.Account.createNew username: req.body.username email: req.body.email password: req.body.password .then ()-> console.log 'ACCOUNT CREATED: ' + req.body.username res.send success: true body: {} , (err)-> res.send success: false body: error: err , (err)-> res.send success: false body: error: err , (err)-> res.send success: false body: error: err else res.send success: false body: error: 'Invalid Parameters ' + JSON.stringify req.body ######################################################################## # Log in '/login' @login = (req, res)-> res.render 'public/login', title: 'Login' @login_submit = (req, res)-> if req.body.email? && req.body.password? app.models.Account.checkLogin email: req.body.email password: req.body.password .then (result)-> req.session.user = result res.send success: true body: username: result.username , (err)-> res.send success: false body: error: err else res.send success: false body: error: 'Invalid Parameters ' + JSON.stringify req.body ######################################################################## # View recipes @recipes = (req, res)-> title = 'Recipes' view = 'public/recipes' search = req.query.search pageNum = req.query.pageNum pageTotal = req.query.pageTotal if search? search = search.replace(/%20/g, ' ').replace(/['"]/g,'').trim() if search < 4 || search > 84 search = undefined if pageNum? && !isNaN(pageNum) pageNum = parseInt pageNum if pageNum < 1 pageNum = 1 else pageNum = 1 if pageTotal? && !isNaN(pageTotal) pageTotal = parseInt pageTotal if pageTotal < 25 || pageTotal > 100 pageTotal = 25 else pageTotal = 25 app.models.Recipe.getSearchSimple pageTotal, pageNum, search .then (result)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal recipes: result.rows totalCount: result.totalCount , (err)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal recipes: [] totalCount: 0 @singleRecipe = (req, res)-> view = 'public/singleRecipe' recipeId = req.params.recipeId if !isNaN recipeId app.models.Recipe.getSingle recipeId .then (result)-> res.render view, title: result.title recipe: result , (err)-> res.redirect '/recipes' else res.redirect '/recipes' ######################################################################## # View ingredients (pages [1,total]) @ingredients = (req, res)-> title = 'Ingredients' view = 'public/ingredients' search = req.query.search pageNum = req.query.pageNum pageTotal = req.query.pageTotal if search? search = search.replace(/%20/g, ' ').replace(/['"]/g,'').trim() if search < 4 || search > 84 search = undefined if pageNum? && !isNaN(pageNum) pageNum = parseInt pageNum if pageNum < 1 pageNum = 1 else pageNum = 1 if pageTotal? && !isNaN(pageTotal) pageTotal = parseInt pageTotal if pageTotal < 25 || pageTotal > 100 pageTotal = 25 else pageTotal = 25 app.models.Ingredient.getSearchSimple pageTotal, pageNum, search .then (result)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal ingredients: result.rows totalCount: result.totalCount , (err)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal ingredients: [] totalCount: 0 @singleIngredient = (req, res)-> view = 'public/singleIngredient' ingredientId = req.params.ingredientId if !isNaN ingredientId app.models.Ingredient.getSingle ingredientId .then (result)-> res.render view, title: result.name ingredient: result , (err)-> res.redirect '/ingredients' else res.redirect '/ingredients'
204537
module.exports = (app) -> class app.PublicController @index = (req, res) -> res.render 'index', title: 'Home' ######################################################################## # Sign up '/signup' @signup = (req, res)-> res.render 'public/signup', title: 'Signup' @signup_submit = (req, res)-> if req.body.username? && req.body.email? && req.body.password? app.models.Account.checkUsernameUnused req.body.username .then ()-> app.models.Account.checkEmailUnused req.body.email .then ()-> # Looks good, create it app.models.Account.createNew username: req.body.username email: req.body.email password: <PASSWORD> .then ()-> console.log 'ACCOUNT CREATED: ' + req.body.username res.send success: true body: {} , (err)-> res.send success: false body: error: err , (err)-> res.send success: false body: error: err , (err)-> res.send success: false body: error: err else res.send success: false body: error: 'Invalid Parameters ' + JSON.stringify req.body ######################################################################## # Log in '/login' @login = (req, res)-> res.render 'public/login', title: 'Login' @login_submit = (req, res)-> if req.body.email? && req.body.password? app.models.Account.checkLogin email: req.body.email password: <PASSWORD> .then (result)-> req.session.user = result res.send success: true body: username: result.username , (err)-> res.send success: false body: error: err else res.send success: false body: error: 'Invalid Parameters ' + JSON.stringify req.body ######################################################################## # View recipes @recipes = (req, res)-> title = 'Recipes' view = 'public/recipes' search = req.query.search pageNum = req.query.pageNum pageTotal = req.query.pageTotal if search? search = search.replace(/%20/g, ' ').replace(/['"]/g,'').trim() if search < 4 || search > 84 search = undefined if pageNum? && !isNaN(pageNum) pageNum = parseInt pageNum if pageNum < 1 pageNum = 1 else pageNum = 1 if pageTotal? && !isNaN(pageTotal) pageTotal = parseInt pageTotal if pageTotal < 25 || pageTotal > 100 pageTotal = 25 else pageTotal = 25 app.models.Recipe.getSearchSimple pageTotal, pageNum, search .then (result)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal recipes: result.rows totalCount: result.totalCount , (err)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal recipes: [] totalCount: 0 @singleRecipe = (req, res)-> view = 'public/singleRecipe' recipeId = req.params.recipeId if !isNaN recipeId app.models.Recipe.getSingle recipeId .then (result)-> res.render view, title: result.title recipe: result , (err)-> res.redirect '/recipes' else res.redirect '/recipes' ######################################################################## # View ingredients (pages [1,total]) @ingredients = (req, res)-> title = 'Ingredients' view = 'public/ingredients' search = req.query.search pageNum = req.query.pageNum pageTotal = req.query.pageTotal if search? search = search.replace(/%20/g, ' ').replace(/['"]/g,'').trim() if search < 4 || search > 84 search = undefined if pageNum? && !isNaN(pageNum) pageNum = parseInt pageNum if pageNum < 1 pageNum = 1 else pageNum = 1 if pageTotal? && !isNaN(pageTotal) pageTotal = parseInt pageTotal if pageTotal < 25 || pageTotal > 100 pageTotal = 25 else pageTotal = 25 app.models.Ingredient.getSearchSimple pageTotal, pageNum, search .then (result)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal ingredients: result.rows totalCount: result.totalCount , (err)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal ingredients: [] totalCount: 0 @singleIngredient = (req, res)-> view = 'public/singleIngredient' ingredientId = req.params.ingredientId if !isNaN ingredientId app.models.Ingredient.getSingle ingredientId .then (result)-> res.render view, title: result.name ingredient: result , (err)-> res.redirect '/ingredients' else res.redirect '/ingredients'
true
module.exports = (app) -> class app.PublicController @index = (req, res) -> res.render 'index', title: 'Home' ######################################################################## # Sign up '/signup' @signup = (req, res)-> res.render 'public/signup', title: 'Signup' @signup_submit = (req, res)-> if req.body.username? && req.body.email? && req.body.password? app.models.Account.checkUsernameUnused req.body.username .then ()-> app.models.Account.checkEmailUnused req.body.email .then ()-> # Looks good, create it app.models.Account.createNew username: req.body.username email: req.body.email password: PI:PASSWORD:<PASSWORD>END_PI .then ()-> console.log 'ACCOUNT CREATED: ' + req.body.username res.send success: true body: {} , (err)-> res.send success: false body: error: err , (err)-> res.send success: false body: error: err , (err)-> res.send success: false body: error: err else res.send success: false body: error: 'Invalid Parameters ' + JSON.stringify req.body ######################################################################## # Log in '/login' @login = (req, res)-> res.render 'public/login', title: 'Login' @login_submit = (req, res)-> if req.body.email? && req.body.password? app.models.Account.checkLogin email: req.body.email password: PI:PASSWORD:<PASSWORD>END_PI .then (result)-> req.session.user = result res.send success: true body: username: result.username , (err)-> res.send success: false body: error: err else res.send success: false body: error: 'Invalid Parameters ' + JSON.stringify req.body ######################################################################## # View recipes @recipes = (req, res)-> title = 'Recipes' view = 'public/recipes' search = req.query.search pageNum = req.query.pageNum pageTotal = req.query.pageTotal if search? search = search.replace(/%20/g, ' ').replace(/['"]/g,'').trim() if search < 4 || search > 84 search = undefined if pageNum? && !isNaN(pageNum) pageNum = parseInt pageNum if pageNum < 1 pageNum = 1 else pageNum = 1 if pageTotal? && !isNaN(pageTotal) pageTotal = parseInt pageTotal if pageTotal < 25 || pageTotal > 100 pageTotal = 25 else pageTotal = 25 app.models.Recipe.getSearchSimple pageTotal, pageNum, search .then (result)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal recipes: result.rows totalCount: result.totalCount , (err)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal recipes: [] totalCount: 0 @singleRecipe = (req, res)-> view = 'public/singleRecipe' recipeId = req.params.recipeId if !isNaN recipeId app.models.Recipe.getSingle recipeId .then (result)-> res.render view, title: result.title recipe: result , (err)-> res.redirect '/recipes' else res.redirect '/recipes' ######################################################################## # View ingredients (pages [1,total]) @ingredients = (req, res)-> title = 'Ingredients' view = 'public/ingredients' search = req.query.search pageNum = req.query.pageNum pageTotal = req.query.pageTotal if search? search = search.replace(/%20/g, ' ').replace(/['"]/g,'').trim() if search < 4 || search > 84 search = undefined if pageNum? && !isNaN(pageNum) pageNum = parseInt pageNum if pageNum < 1 pageNum = 1 else pageNum = 1 if pageTotal? && !isNaN(pageTotal) pageTotal = parseInt pageTotal if pageTotal < 25 || pageTotal > 100 pageTotal = 25 else pageTotal = 25 app.models.Ingredient.getSearchSimple pageTotal, pageNum, search .then (result)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal ingredients: result.rows totalCount: result.totalCount , (err)-> res.render view, title: title isSearch: search? search: search pageNum: pageNum pageTotal: pageTotal ingredients: [] totalCount: 0 @singleIngredient = (req, res)-> view = 'public/singleIngredient' ingredientId = req.params.ingredientId if !isNaN ingredientId app.models.Ingredient.getSingle ingredientId .then (result)-> res.render view, title: result.name ingredient: result , (err)-> res.redirect '/ingredients' else res.redirect '/ingredients'
[ { "context": "= new Thorax.Views.InputStringView(initialValue: 'bonnie test', allowNull: false)\n view.render()\n\n ex", "end": 446, "score": 0.9997729659080505, "start": 435, "tag": "NAME", "value": "bonnie test" }, { "context": "Value()).toBe true\n expect(view.value).toBe 'bonnie test'\n expect(view.$('input').val()).toEqual 'bon", "end": 575, "score": 0.9997357726097107, "start": 564, "tag": "NAME", "value": "bonnie test" }, { "context": "est'\n expect(view.$('input').val()).toEqual 'bonnie test'\n\n it 'starts with invalid null, with allowNul", "end": 633, "score": 0.9997323155403137, "start": 622, "tag": "NAME", "value": "bonnie test" }, { "context": "view.value).toBe null\n\n view.$('input').val('test string').change()\n\n expect(view.trigger).toHaveBeen", "end": 1276, "score": 0.982981264591217, "start": 1265, "tag": "NAME", "value": "test string" } ]
spec/javascripts/patient_builder_tests/input_views/string_input_view_spec.js.coffee
projectcypress/bonnie
33
describe 'InputView', -> describe 'StringView', -> it 'starts with valid null, default params', -> view = new Thorax.Views.InputStringView() view.render() expect(view.hasValidValue()).toBe true expect(view.value).toBe null expect(view.$('input').prop('placeholder')).toEqual 'string' it 'starts with valid initial value', -> view = new Thorax.Views.InputStringView(initialValue: 'bonnie test', allowNull: false) view.render() expect(view.hasValidValue()).toBe true expect(view.value).toBe 'bonnie test' expect(view.$('input').val()).toEqual 'bonnie test' it 'starts with invalid null, with allowNull false, custom placeholder', -> view = new Thorax.Views.InputStringView(allowNull: false, placeholder: 'this is a string') view.render() expect(view.hasValidValue()).toBe false expect(view.value).toBe null expect(view.$('input').prop('placeholder')).toEqual 'this is a string' it 'value bcomes valid after entry', -> view = new Thorax.Views.InputStringView(allowNull: false) view.render() spyOn(view, 'trigger') expect(view.hasValidValue()).toBe false expect(view.value).toBe null view.$('input').val('test string').change() expect(view.trigger).toHaveBeenCalledWith('valueChanged', view) expect(view.hasValidValue()).toBe true expect(view.value).toBe 'test string' it 'value bcomes null and invalid after empty string is entered', -> view = new Thorax.Views.InputStringView(initialValue: 'starting string', allowNull: false) view.render() spyOn(view, 'trigger') expect(view.hasValidValue()).toBe true expect(view.value).toBe 'starting string' view.$('input').val('').change() expect(view.trigger).toHaveBeenCalledWith('valueChanged', view) expect(view.hasValidValue()).toBe false expect(view.value).toBe null
21230
describe 'InputView', -> describe 'StringView', -> it 'starts with valid null, default params', -> view = new Thorax.Views.InputStringView() view.render() expect(view.hasValidValue()).toBe true expect(view.value).toBe null expect(view.$('input').prop('placeholder')).toEqual 'string' it 'starts with valid initial value', -> view = new Thorax.Views.InputStringView(initialValue: '<NAME>', allowNull: false) view.render() expect(view.hasValidValue()).toBe true expect(view.value).toBe '<NAME>' expect(view.$('input').val()).toEqual '<NAME>' it 'starts with invalid null, with allowNull false, custom placeholder', -> view = new Thorax.Views.InputStringView(allowNull: false, placeholder: 'this is a string') view.render() expect(view.hasValidValue()).toBe false expect(view.value).toBe null expect(view.$('input').prop('placeholder')).toEqual 'this is a string' it 'value bcomes valid after entry', -> view = new Thorax.Views.InputStringView(allowNull: false) view.render() spyOn(view, 'trigger') expect(view.hasValidValue()).toBe false expect(view.value).toBe null view.$('input').val('<NAME>').change() expect(view.trigger).toHaveBeenCalledWith('valueChanged', view) expect(view.hasValidValue()).toBe true expect(view.value).toBe 'test string' it 'value bcomes null and invalid after empty string is entered', -> view = new Thorax.Views.InputStringView(initialValue: 'starting string', allowNull: false) view.render() spyOn(view, 'trigger') expect(view.hasValidValue()).toBe true expect(view.value).toBe 'starting string' view.$('input').val('').change() expect(view.trigger).toHaveBeenCalledWith('valueChanged', view) expect(view.hasValidValue()).toBe false expect(view.value).toBe null
true
describe 'InputView', -> describe 'StringView', -> it 'starts with valid null, default params', -> view = new Thorax.Views.InputStringView() view.render() expect(view.hasValidValue()).toBe true expect(view.value).toBe null expect(view.$('input').prop('placeholder')).toEqual 'string' it 'starts with valid initial value', -> view = new Thorax.Views.InputStringView(initialValue: 'PI:NAME:<NAME>END_PI', allowNull: false) view.render() expect(view.hasValidValue()).toBe true expect(view.value).toBe 'PI:NAME:<NAME>END_PI' expect(view.$('input').val()).toEqual 'PI:NAME:<NAME>END_PI' it 'starts with invalid null, with allowNull false, custom placeholder', -> view = new Thorax.Views.InputStringView(allowNull: false, placeholder: 'this is a string') view.render() expect(view.hasValidValue()).toBe false expect(view.value).toBe null expect(view.$('input').prop('placeholder')).toEqual 'this is a string' it 'value bcomes valid after entry', -> view = new Thorax.Views.InputStringView(allowNull: false) view.render() spyOn(view, 'trigger') expect(view.hasValidValue()).toBe false expect(view.value).toBe null view.$('input').val('PI:NAME:<NAME>END_PI').change() expect(view.trigger).toHaveBeenCalledWith('valueChanged', view) expect(view.hasValidValue()).toBe true expect(view.value).toBe 'test string' it 'value bcomes null and invalid after empty string is entered', -> view = new Thorax.Views.InputStringView(initialValue: 'starting string', allowNull: false) view.render() spyOn(view, 'trigger') expect(view.hasValidValue()).toBe true expect(view.value).toBe 'starting string' view.$('input').val('').change() expect(view.trigger).toHaveBeenCalledWith('valueChanged', view) expect(view.hasValidValue()).toBe false expect(view.value).toBe null
[ { "context": "okieParser()\n\n\tapp.use express.session\n\t\tsecret:\t'ozclient'\n\t\tcookie:\n\t\t\tmaxAge:\tnull\n\n\tapp.use app.router\n\n", "end": 379, "score": 0.5584929585456848, "start": 371, "tag": "KEY", "value": "ozclient" } ]
server/server.coffee
standart-n/sn-oz-client
0
express = require('express') colors = require('colors') http = require('http') path = require('path') fs = require('fs') port = 3000 app = express() app.configure -> app.use express.logger 'dev' app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session secret: 'ozclient' cookie: maxAge: null app.use app.router app.use express.static __dirname + '/' app.get '/', (req, res) -> fs.readFile 'index.html', (err, data) -> res.send 'error!' if err res.set 'Vary': 'Accept-Encoding' 'Content-Type': 'text/html' res.send data app.listen port, () -> console.log "server work at ".grey + "http://localhost:#{port.toString()}".blue
602
express = require('express') colors = require('colors') http = require('http') path = require('path') fs = require('fs') port = 3000 app = express() app.configure -> app.use express.logger 'dev' app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session secret: '<KEY>' cookie: maxAge: null app.use app.router app.use express.static __dirname + '/' app.get '/', (req, res) -> fs.readFile 'index.html', (err, data) -> res.send 'error!' if err res.set 'Vary': 'Accept-Encoding' 'Content-Type': 'text/html' res.send data app.listen port, () -> console.log "server work at ".grey + "http://localhost:#{port.toString()}".blue
true
express = require('express') colors = require('colors') http = require('http') path = require('path') fs = require('fs') port = 3000 app = express() app.configure -> app.use express.logger 'dev' app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session secret: 'PI:KEY:<KEY>END_PI' cookie: maxAge: null app.use app.router app.use express.static __dirname + '/' app.get '/', (req, res) -> fs.readFile 'index.html', (err, data) -> res.send 'error!' if err res.set 'Vary': 'Accept-Encoding' 'Content-Type': 'text/html' res.send data app.listen port, () -> console.log "server work at ".grey + "http://localhost:#{port.toString()}".blue
[ { "context": "{\n name: 'Drunk Marine Students'\n author: 'Geronimoo'\n requires: ['Potion', 'Un", "end": 32, "score": 0.9997068643569946, "start": 11, "tag": "NAME", "value": "Drunk Marine Students" }, { "context": "{\n name: 'Drunk Marine Students'\n author: 'Geronimoo'\n requires: ['Potion', 'University', 'Vineyard',", "end": 54, "score": 0.9998683333396912, "start": 45, "tag": "NAME", "value": "Geronimoo" } ]
strategies/DrunkenMarineStudents.coffee
rspeer/dominiate
65
{ name: 'Drunk Marine Students' author: 'Geronimoo' requires: ['Potion', 'University', 'Vineyard', 'Wharf', 'Alchemist', 'Bazaar', 'Wharf'] gainPriority: (state, my) -> [ "Vineyard" if my.numActionCardsInDeck() > 11 "Province" "Duchy" if state.countInSupply("Province") <= 2 "Estate" if state.countInSupply("Province") <= 1 "University" if my.countInDeck("University") < 3 "Wharf" if my.countInDeck("University") + my.countInDeck("Bazaar") > my.countInDeck("Wharf") "Scrying Pool" if my.numActionCardsInDeck() > 3 "Alchemist" "Bazaar" "Potion" if my.countInDeck("Potion") < 3 "Silver" ] }
131416
{ name: '<NAME>' author: '<NAME>' requires: ['Potion', 'University', 'Vineyard', 'Wharf', 'Alchemist', 'Bazaar', 'Wharf'] gainPriority: (state, my) -> [ "Vineyard" if my.numActionCardsInDeck() > 11 "Province" "Duchy" if state.countInSupply("Province") <= 2 "Estate" if state.countInSupply("Province") <= 1 "University" if my.countInDeck("University") < 3 "Wharf" if my.countInDeck("University") + my.countInDeck("Bazaar") > my.countInDeck("Wharf") "Scrying Pool" if my.numActionCardsInDeck() > 3 "Alchemist" "Bazaar" "Potion" if my.countInDeck("Potion") < 3 "Silver" ] }
true
{ name: 'PI:NAME:<NAME>END_PI' author: 'PI:NAME:<NAME>END_PI' requires: ['Potion', 'University', 'Vineyard', 'Wharf', 'Alchemist', 'Bazaar', 'Wharf'] gainPriority: (state, my) -> [ "Vineyard" if my.numActionCardsInDeck() > 11 "Province" "Duchy" if state.countInSupply("Province") <= 2 "Estate" if state.countInSupply("Province") <= 1 "University" if my.countInDeck("University") < 3 "Wharf" if my.countInDeck("University") + my.countInDeck("Bazaar") > my.countInDeck("Wharf") "Scrying Pool" if my.numActionCardsInDeck() > 3 "Alchemist" "Bazaar" "Potion" if my.countInDeck("Potion") < 3 "Silver" ] }
[ { "context": "->\n ops = options()\n ops.body =\n firstName: 'Test'\n lastName: 'User'\n email: testUserEmail\n ", "end": 377, "score": 0.9994944334030151, "start": 373, "tag": "NAME", "value": "Test" }, { "context": " ops.body =\n firstName: 'Test'\n lastName: 'User'\n email: testUserEmail\n password: 'keyboard", "end": 398, "score": 0.99953293800354, "start": 394, "tag": "NAME", "value": "User" }, { "context": "e: 'User'\n email: testUserEmail\n password: 'keyboard cats'\n request.post (base '/users'), ops, (e,r,b)->\n ", "end": 453, "score": 0.9992506504058838, "start": 440, "tag": "PASSWORD", "value": "keyboard cats" }, { "context": "()\n\n it 'Creates a new user', (done) ->\n t = \"testUser#{uuid.v1()}@testuser.com\"\n makeUser t, 200, (b)->\n UserTestHelper.", "end": 1147, "score": 0.9309388399124146, "start": 1114, "tag": "EMAIL", "value": "testUser#{uuid.v1()}@testuser.com" }, { "context": "two users with the same email', (done)->\n t = \"testUser#{uuid.v1()}@testuser.com\"\n makeUser t, 200, -> makeUser", "end": 1673, "score": 0.8455552458763123, "start": 1656, "tag": "EMAIL", "value": "testUser#{uuid.v1" }, { "context": "mail', (done)->\n t = \"testUser#{uuid.v1()}@testuser.com\"\n makeUser t, 200, -> makeUser t, 400, (error)", "end": 1689, "score": 0.9997302889823914, "start": 1681, "tag": "EMAIL", "value": "user.com" }, { "context": "ne()\n\n it 'can delete a user', (done)->\n t = \"testUser#{uuid.v1()}@testuser.com\"\n makeUser t, 200, (user)->\n request.del ", "end": 1897, "score": 0.9338845610618591, "start": 1864, "tag": "EMAIL", "value": "testUser#{uuid.v1()}@testuser.com" }, { "context": "not be able to access another', (done)->\n t = \"t#{uuid.v1()}@testuser.com\"\n b = \"b#{uuid.v1()}@testuser.com\"\n d = \"d#", "end": 2470, "score": 0.922083854675293, "start": 2444, "tag": "EMAIL", "value": "t#{uuid.v1()}@testuser.com" }, { "context": ")->\n t = \"t#{uuid.v1()}@testuser.com\"\n b = \"b#{uuid.v1()}@testuser.com\"\n d = \"d#{uuid.v1()}@testuser.com\"\n async.m", "end": 2507, "score": 0.8294373154640198, "start": 2481, "tag": "EMAIL", "value": "b#{uuid.v1()}@testuser.com" }, { "context": "om\"\n b = \"b#{uuid.v1()}@testuser.com\"\n d = \"d#{uuid.v1()}@testuser.com\"\n async.map [b,t, d], (u, cb)-", "end": 2528, "score": 0.7773311734199524, "start": 2518, "tag": "EMAIL", "value": "d#{uuid.v1" }, { "context": "b#{uuid.v1()}@testuser.com\"\n d = \"d#{uuid.v1()}@testuser.com\"\n async.map [b,t, d], (u, cb)->\n makeUser", "end": 2544, "score": 0.968120276927948, "start": 2531, "tag": "EMAIL", "value": "@testuser.com" } ]
test/routes/users.coffee
t3mpus/tempus-api
3
request = require 'request' async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' startApp = require './../start_app' base = require './../base' options = require './../options' UserTestHelper = require './user_test_helper' testUsers = [] makeUser = (testUserEmail, status, cb)-> ops = options() ops.body = firstName: 'Test' lastName: 'User' email: testUserEmail password: 'keyboard cats' request.post (base '/users'), ops, (e,r,b)-> r.statusCode.should.be.equal status UserTestHelper.validate b if r.statusCode is 200 testUsers.push b if r.statusCode is 200 cb(b) describe 'Users', -> before (done) -> startApp -> done() after (done) -> async.each testUsers, (u, cb)-> request.del (base "/users/#{u.id}"), options(u), (e,r,b)-> r.statusCode.should.be.equal 200 cb() , done it 'Get all Users', (done)-> #Will require an Admin account request (base '/users'), options(), (e,r,b)-> r.statusCode.should.be.equal 404 done() it 'Creates a new user', (done) -> t = "testUser#{uuid.v1()}@testuser.com" makeUser t, 200, (b)-> UserTestHelper.validate b b.should.have.property 'credentials' b.credentials.should.have.property 'secret' done() it 'can get each user individually', (done)-> iterator = (u, cb)-> request (base "/users/#{u.id}"), options(u), (e,r,b)-> r.statusCode.should.be.equal 200 UserTestHelper.validate b cb() async.eachLimit testUsers, 100, iterator, done it 'cant have two users with the same email', (done)-> t = "testUser#{uuid.v1()}@testuser.com" makeUser t, 200, -> makeUser t, 400, (error)-> error.should.have.property 'error', 'user already exists' done() it 'can delete a user', (done)-> t = "testUser#{uuid.v1()}@testuser.com" makeUser t, 200, (user)-> request.del (base "/users/#{user.id}"), options(user), (e,r,b)-> r.statusCode.should.be.equal 200 request (base "/users/#{user.id}"), options(user), (e,r,b)-> testUsers = _.without(testUsers, user) r.statusCode.should.be.equal 401 done() it 'can handle a non existent user', (done)-> request (base "/users/not-an-id"), options(), (e,r,b)-> r.statusCode.should.be.equal 401 done() it 'should not be able to access another', (done)-> t = "t#{uuid.v1()}@testuser.com" b = "b#{uuid.v1()}@testuser.com" d = "d#{uuid.v1()}@testuser.com" async.map [b,t, d], (u, cb)-> makeUser u, 200, (u)-> cb null, u , (err, users) -> differentUser = _.last(users) users = _.without(users, differentUser) async.eachSeries users, (e,cb)-> request (base "/users/#{e.id}"), options(differentUser), (e,r,b)-> r.statusCode.should.be.equal 403 cb() , done
143312
request = require 'request' async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' startApp = require './../start_app' base = require './../base' options = require './../options' UserTestHelper = require './user_test_helper' testUsers = [] makeUser = (testUserEmail, status, cb)-> ops = options() ops.body = firstName: '<NAME>' lastName: '<NAME>' email: testUserEmail password: '<PASSWORD>' request.post (base '/users'), ops, (e,r,b)-> r.statusCode.should.be.equal status UserTestHelper.validate b if r.statusCode is 200 testUsers.push b if r.statusCode is 200 cb(b) describe 'Users', -> before (done) -> startApp -> done() after (done) -> async.each testUsers, (u, cb)-> request.del (base "/users/#{u.id}"), options(u), (e,r,b)-> r.statusCode.should.be.equal 200 cb() , done it 'Get all Users', (done)-> #Will require an Admin account request (base '/users'), options(), (e,r,b)-> r.statusCode.should.be.equal 404 done() it 'Creates a new user', (done) -> t = "<EMAIL>" makeUser t, 200, (b)-> UserTestHelper.validate b b.should.have.property 'credentials' b.credentials.should.have.property 'secret' done() it 'can get each user individually', (done)-> iterator = (u, cb)-> request (base "/users/#{u.id}"), options(u), (e,r,b)-> r.statusCode.should.be.equal 200 UserTestHelper.validate b cb() async.eachLimit testUsers, 100, iterator, done it 'cant have two users with the same email', (done)-> t = "<EMAIL>()}@test<EMAIL>" makeUser t, 200, -> makeUser t, 400, (error)-> error.should.have.property 'error', 'user already exists' done() it 'can delete a user', (done)-> t = "<EMAIL>" makeUser t, 200, (user)-> request.del (base "/users/#{user.id}"), options(user), (e,r,b)-> r.statusCode.should.be.equal 200 request (base "/users/#{user.id}"), options(user), (e,r,b)-> testUsers = _.without(testUsers, user) r.statusCode.should.be.equal 401 done() it 'can handle a non existent user', (done)-> request (base "/users/not-an-id"), options(), (e,r,b)-> r.statusCode.should.be.equal 401 done() it 'should not be able to access another', (done)-> t = "<EMAIL>" b = "<EMAIL>" d = "<EMAIL>()}<EMAIL>" async.map [b,t, d], (u, cb)-> makeUser u, 200, (u)-> cb null, u , (err, users) -> differentUser = _.last(users) users = _.without(users, differentUser) async.eachSeries users, (e,cb)-> request (base "/users/#{e.id}"), options(differentUser), (e,r,b)-> r.statusCode.should.be.equal 403 cb() , done
true
request = require 'request' async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' startApp = require './../start_app' base = require './../base' options = require './../options' UserTestHelper = require './user_test_helper' testUsers = [] makeUser = (testUserEmail, status, cb)-> ops = options() ops.body = firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' email: testUserEmail password: 'PI:PASSWORD:<PASSWORD>END_PI' request.post (base '/users'), ops, (e,r,b)-> r.statusCode.should.be.equal status UserTestHelper.validate b if r.statusCode is 200 testUsers.push b if r.statusCode is 200 cb(b) describe 'Users', -> before (done) -> startApp -> done() after (done) -> async.each testUsers, (u, cb)-> request.del (base "/users/#{u.id}"), options(u), (e,r,b)-> r.statusCode.should.be.equal 200 cb() , done it 'Get all Users', (done)-> #Will require an Admin account request (base '/users'), options(), (e,r,b)-> r.statusCode.should.be.equal 404 done() it 'Creates a new user', (done) -> t = "PI:EMAIL:<EMAIL>END_PI" makeUser t, 200, (b)-> UserTestHelper.validate b b.should.have.property 'credentials' b.credentials.should.have.property 'secret' done() it 'can get each user individually', (done)-> iterator = (u, cb)-> request (base "/users/#{u.id}"), options(u), (e,r,b)-> r.statusCode.should.be.equal 200 UserTestHelper.validate b cb() async.eachLimit testUsers, 100, iterator, done it 'cant have two users with the same email', (done)-> t = "PI:EMAIL:<EMAIL>END_PI()}@testPI:EMAIL:<EMAIL>END_PI" makeUser t, 200, -> makeUser t, 400, (error)-> error.should.have.property 'error', 'user already exists' done() it 'can delete a user', (done)-> t = "PI:EMAIL:<EMAIL>END_PI" makeUser t, 200, (user)-> request.del (base "/users/#{user.id}"), options(user), (e,r,b)-> r.statusCode.should.be.equal 200 request (base "/users/#{user.id}"), options(user), (e,r,b)-> testUsers = _.without(testUsers, user) r.statusCode.should.be.equal 401 done() it 'can handle a non existent user', (done)-> request (base "/users/not-an-id"), options(), (e,r,b)-> r.statusCode.should.be.equal 401 done() it 'should not be able to access another', (done)-> t = "PI:EMAIL:<EMAIL>END_PI" b = "PI:EMAIL:<EMAIL>END_PI" d = "PI:EMAIL:<EMAIL>END_PI()}PI:EMAIL:<EMAIL>END_PI" async.map [b,t, d], (u, cb)-> makeUser u, 200, (u)-> cb null, u , (err, users) -> differentUser = _.last(users) users = _.without(users, differentUser) async.eachSeries users, (e,cb)-> request (base "/users/#{e.id}"), options(differentUser), (e,r,b)-> r.statusCode.should.be.equal 403 cb() , done
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9984757304191589, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-dgram-bind-shared-ports.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # TODO XXX FIXME when windows supports clustered dgram ports re-enable this # test noop = -> common = require("../common") assert = require("assert") cluster = require("cluster") dgram = require("dgram") process.exit 0 if process.platform is "win32" if cluster.isMaster worker1 = cluster.fork() worker1.on "message", (msg) -> assert.equal msg, "success" worker2 = cluster.fork() worker2.on "message", (msg) -> assert.equal msg, "socket2:EADDRINUSE" worker1.kill() worker2.kill() return return else socket1 = dgram.createSocket("udp4", noop) socket2 = dgram.createSocket("udp4", noop) socket1.on "error", (err) -> # no errors expected process.send "socket1:" + err.code return socket2.on "error", (err) -> # an error is expected on the second worker process.send "socket2:" + err.code return socket1.bind address: "localhost" port: common.PORT exclusive: false , -> socket2.bind port: common.PORT + 1 exclusive: true , -> # the first worker should succeed process.send "success" return return
49394
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # TODO XXX FIXME when windows supports clustered dgram ports re-enable this # test noop = -> common = require("../common") assert = require("assert") cluster = require("cluster") dgram = require("dgram") process.exit 0 if process.platform is "win32" if cluster.isMaster worker1 = cluster.fork() worker1.on "message", (msg) -> assert.equal msg, "success" worker2 = cluster.fork() worker2.on "message", (msg) -> assert.equal msg, "socket2:EADDRINUSE" worker1.kill() worker2.kill() return return else socket1 = dgram.createSocket("udp4", noop) socket2 = dgram.createSocket("udp4", noop) socket1.on "error", (err) -> # no errors expected process.send "socket1:" + err.code return socket2.on "error", (err) -> # an error is expected on the second worker process.send "socket2:" + err.code return socket1.bind address: "localhost" port: common.PORT exclusive: false , -> socket2.bind port: common.PORT + 1 exclusive: true , -> # the first worker should succeed process.send "success" return return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # TODO XXX FIXME when windows supports clustered dgram ports re-enable this # test noop = -> common = require("../common") assert = require("assert") cluster = require("cluster") dgram = require("dgram") process.exit 0 if process.platform is "win32" if cluster.isMaster worker1 = cluster.fork() worker1.on "message", (msg) -> assert.equal msg, "success" worker2 = cluster.fork() worker2.on "message", (msg) -> assert.equal msg, "socket2:EADDRINUSE" worker1.kill() worker2.kill() return return else socket1 = dgram.createSocket("udp4", noop) socket2 = dgram.createSocket("udp4", noop) socket1.on "error", (err) -> # no errors expected process.send "socket1:" + err.code return socket2.on "error", (err) -> # an error is expected on the second worker process.send "socket2:" + err.code return socket1.bind address: "localhost" port: common.PORT exclusive: false , -> socket2.bind port: common.PORT + 1 exclusive: true , -> # the first worker should succeed process.send "success" return return
[ { "context": "key { color: #c66c75; }\n.key { color: #c7ccd4; }\n.value { color: #d5927b; }\n\n\n/* \n ", "end": 1162, "score": 0.5845543146133423, "start": 1161, "tag": "KEY", "value": "7" }, { "context": " * I mean *I* did it, but you know, whatever...\n * jake albaugh definitely did not have anything \n * to do with t", "end": 4428, "score": 0.940949559211731, "start": 4416, "tag": "NAME", "value": "jake albaugh" } ]
codepen.coffee
stormluke/melonwithluke
0
styles = """ /* * "Myself" v1.0.4 * Robot rights protected under BOT License * Authored by pen#PwLXXP */ body { background-color: #1a1c24; color: #fff; font-size: 13px; line-height: 1.4; -webkit-font-smoothing: subpixel-antialiased; } /* ... * * ...hello? * * Oh hai guys! It's me, pen#PwLXXP. * * I'm just sitting here coding away. * * Sure, you can watch. * * * This CSS is being injected into a DOM <style> element * and written in this <pre> element simultaneously. * * Confused? Watch! * */ pre { position: fixed; width: 48%; top: 30px; bottom: 30px; left: 26%; transition: left 500ms; background-color: #313744; color: #a6c3d4; border: 1px solid rgba(0,0,0,0.2); padding: 24px 12px; box-sizing: border-box; border-radius: 3px; box-shadow: 0px 4px 0px 2px rgba(0,0,0,0.1); } /* * Syntax highlighting * Colors based on Base16 Ocean Dark */ pre em:not(.comment) { font-style: normal; } .comment { color: #707e84; } .selector { color: #c66c75; } .selector .key { color: #c66c75; } .key { color: #c7ccd4; } .value { color: #d5927b; } /* * Let's build my little pen heart. */ /* First, we'll move this s*** over */ pre { left: 50%; } /* Now we can build my heart */ #heart, #echo { position: fixed; width: 300px; height: 300px; top: calc(50% - 150px); left: calc(25% - 150px); text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } #heart { z-index: 8; } #echo { z-index: 7; } #heart::before, #heart::after, #echo::before, #echo::after { content: ''; position: absolute; top: 40px; width: 150px; height: 240px; background: #c66c75; border-radius: 150px 150px 0 0; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; transform-origin: 0 100%; } #heart::before, #echo::before { left: 150px; } #heart::after, #echo::after { left: 0; -webkit-transform: rotate(45deg); transform: rotate(45deg); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; } /* It needs some depth */ #heart::after { box-shadow: inset -6px -6px 0px 6px rgba(255,255,255,0.1); } #heart::before { box-shadow: inset 6px 6px 0px 6px rgba(255,255,255,0.1); } /* Makin it mine. */ #heart i::before { content: 'melon&luke'; position: absolute; z-index: 9; width: 100%; top: 35%; left: 0; font-style: normal; color: rgba(255,255,255,0.8); font-weight: 100; font-size: 30px; text-shadow: -1px -1px 0px rgba(0,0,0,0.2); } /* * Hearts gotta beat. */ @-webkit-keyframes heartbeat { 0%, 100% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { -webkit-transform: scale(1.00); transform: scale(1.00); } } @keyframes heartbeat { 0%, 100% { transform: scale(0.95); } 50% { transform: scale(1.00); } } @-webkit-keyframes echo { 0% { opacity: 0.1; -webkit-transform: scale(1); transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(1.4); transform: scale(1.4); } } @keyframes echo { 0% { opacity: 0.1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.4); } } /* * Beautiful! Now for the beating... */ #heart, #echo { -webkit-animation-duration: 2000ms; animation-duration: 2000ms; -webkit-animation-timing-function: cubic-bezier(0, 0, 0, 1.74); animation-timing-function: cubic-bezier(0, 0, 0, 1.74); -webkit-animation-delay: 500ms; animation-delay: 500ms; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-play-state: paused; animation-play-state: paused; } #heart { -webkit-animation-name: heartbeat; animation-name: heartbeat; } #echo { -webkit-animation-name: echo; animation-name: echo; } /* * Ready... */ #heart, #echo { /* * ...set... */ -webkit-animation-play-state: running; animation-play-state: running; /* * ...beat! */ } /* * * Wahoo! * * We did it! * * I mean *I* did it, but you know, whatever... * jake albaugh definitely did not have anything * to do with this. * * This pen loves CodePen! * * See you later! * */ """ openComment = false writeStyleChar = (which) -> # begin wrapping open comments if which == '/' && openComment == false openComment = true styles = $('#style-text').html() + which else if which == '/' && openComment == true openComment = false styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>') # wrap style declaration else if which == ':' styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:') # wrap style value else if which == ';' styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;') # wrap selector else if which == '{' styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{') else styles = $('#style-text').html() + which $('#style-text').html styles $('#style-tag').append which writeStyles = (message, index, interval) -> if index < message.length pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight writeStyleChar message[index++] setTimeout (-> writeStyles message, index, interval ), interval # appending the tags I'll need. $('body').append """ <style id="style-tag"></style> <span id="echo"></span> <span id="heart"><i></i></span> <pre id="style-text"></pre> """ # faster typing in small iframe on codepen homepage time = if window.innerWidth <= 578 then 4 else 16 # starting it off writeStyles(styles, 0, time) ### Changelog: 1.0.0: i exist! 1.0.1: heart instead of circle 1.0.2: including standard CSS3 transforms and animations was only using `-webkit` to be less verbose (standard transforms dont work in safari) now works in FF 1.0.3: crossbrowser echo nested `scale()` styles (scaled in scaled) only worked in chrome moved echo out of heart to fix 1.0.4: more efficient animations `0%, 100% {}` instead of duplicated keyframes ###
160631
styles = """ /* * "Myself" v1.0.4 * Robot rights protected under BOT License * Authored by pen#PwLXXP */ body { background-color: #1a1c24; color: #fff; font-size: 13px; line-height: 1.4; -webkit-font-smoothing: subpixel-antialiased; } /* ... * * ...hello? * * Oh hai guys! It's me, pen#PwLXXP. * * I'm just sitting here coding away. * * Sure, you can watch. * * * This CSS is being injected into a DOM <style> element * and written in this <pre> element simultaneously. * * Confused? Watch! * */ pre { position: fixed; width: 48%; top: 30px; bottom: 30px; left: 26%; transition: left 500ms; background-color: #313744; color: #a6c3d4; border: 1px solid rgba(0,0,0,0.2); padding: 24px 12px; box-sizing: border-box; border-radius: 3px; box-shadow: 0px 4px 0px 2px rgba(0,0,0,0.1); } /* * Syntax highlighting * Colors based on Base16 Ocean Dark */ pre em:not(.comment) { font-style: normal; } .comment { color: #707e84; } .selector { color: #c66c75; } .selector .key { color: #c66c75; } .key { color: #c<KEY>ccd4; } .value { color: #d5927b; } /* * Let's build my little pen heart. */ /* First, we'll move this s*** over */ pre { left: 50%; } /* Now we can build my heart */ #heart, #echo { position: fixed; width: 300px; height: 300px; top: calc(50% - 150px); left: calc(25% - 150px); text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } #heart { z-index: 8; } #echo { z-index: 7; } #heart::before, #heart::after, #echo::before, #echo::after { content: ''; position: absolute; top: 40px; width: 150px; height: 240px; background: #c66c75; border-radius: 150px 150px 0 0; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; transform-origin: 0 100%; } #heart::before, #echo::before { left: 150px; } #heart::after, #echo::after { left: 0; -webkit-transform: rotate(45deg); transform: rotate(45deg); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; } /* It needs some depth */ #heart::after { box-shadow: inset -6px -6px 0px 6px rgba(255,255,255,0.1); } #heart::before { box-shadow: inset 6px 6px 0px 6px rgba(255,255,255,0.1); } /* Makin it mine. */ #heart i::before { content: 'melon&luke'; position: absolute; z-index: 9; width: 100%; top: 35%; left: 0; font-style: normal; color: rgba(255,255,255,0.8); font-weight: 100; font-size: 30px; text-shadow: -1px -1px 0px rgba(0,0,0,0.2); } /* * Hearts gotta beat. */ @-webkit-keyframes heartbeat { 0%, 100% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { -webkit-transform: scale(1.00); transform: scale(1.00); } } @keyframes heartbeat { 0%, 100% { transform: scale(0.95); } 50% { transform: scale(1.00); } } @-webkit-keyframes echo { 0% { opacity: 0.1; -webkit-transform: scale(1); transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(1.4); transform: scale(1.4); } } @keyframes echo { 0% { opacity: 0.1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.4); } } /* * Beautiful! Now for the beating... */ #heart, #echo { -webkit-animation-duration: 2000ms; animation-duration: 2000ms; -webkit-animation-timing-function: cubic-bezier(0, 0, 0, 1.74); animation-timing-function: cubic-bezier(0, 0, 0, 1.74); -webkit-animation-delay: 500ms; animation-delay: 500ms; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-play-state: paused; animation-play-state: paused; } #heart { -webkit-animation-name: heartbeat; animation-name: heartbeat; } #echo { -webkit-animation-name: echo; animation-name: echo; } /* * Ready... */ #heart, #echo { /* * ...set... */ -webkit-animation-play-state: running; animation-play-state: running; /* * ...beat! */ } /* * * Wahoo! * * We did it! * * I mean *I* did it, but you know, whatever... * <NAME> definitely did not have anything * to do with this. * * This pen loves CodePen! * * See you later! * */ """ openComment = false writeStyleChar = (which) -> # begin wrapping open comments if which == '/' && openComment == false openComment = true styles = $('#style-text').html() + which else if which == '/' && openComment == true openComment = false styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>') # wrap style declaration else if which == ':' styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:') # wrap style value else if which == ';' styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;') # wrap selector else if which == '{' styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{') else styles = $('#style-text').html() + which $('#style-text').html styles $('#style-tag').append which writeStyles = (message, index, interval) -> if index < message.length pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight writeStyleChar message[index++] setTimeout (-> writeStyles message, index, interval ), interval # appending the tags I'll need. $('body').append """ <style id="style-tag"></style> <span id="echo"></span> <span id="heart"><i></i></span> <pre id="style-text"></pre> """ # faster typing in small iframe on codepen homepage time = if window.innerWidth <= 578 then 4 else 16 # starting it off writeStyles(styles, 0, time) ### Changelog: 1.0.0: i exist! 1.0.1: heart instead of circle 1.0.2: including standard CSS3 transforms and animations was only using `-webkit` to be less verbose (standard transforms dont work in safari) now works in FF 1.0.3: crossbrowser echo nested `scale()` styles (scaled in scaled) only worked in chrome moved echo out of heart to fix 1.0.4: more efficient animations `0%, 100% {}` instead of duplicated keyframes ###
true
styles = """ /* * "Myself" v1.0.4 * Robot rights protected under BOT License * Authored by pen#PwLXXP */ body { background-color: #1a1c24; color: #fff; font-size: 13px; line-height: 1.4; -webkit-font-smoothing: subpixel-antialiased; } /* ... * * ...hello? * * Oh hai guys! It's me, pen#PwLXXP. * * I'm just sitting here coding away. * * Sure, you can watch. * * * This CSS is being injected into a DOM <style> element * and written in this <pre> element simultaneously. * * Confused? Watch! * */ pre { position: fixed; width: 48%; top: 30px; bottom: 30px; left: 26%; transition: left 500ms; background-color: #313744; color: #a6c3d4; border: 1px solid rgba(0,0,0,0.2); padding: 24px 12px; box-sizing: border-box; border-radius: 3px; box-shadow: 0px 4px 0px 2px rgba(0,0,0,0.1); } /* * Syntax highlighting * Colors based on Base16 Ocean Dark */ pre em:not(.comment) { font-style: normal; } .comment { color: #707e84; } .selector { color: #c66c75; } .selector .key { color: #c66c75; } .key { color: #cPI:KEY:<KEY>END_PIccd4; } .value { color: #d5927b; } /* * Let's build my little pen heart. */ /* First, we'll move this s*** over */ pre { left: 50%; } /* Now we can build my heart */ #heart, #echo { position: fixed; width: 300px; height: 300px; top: calc(50% - 150px); left: calc(25% - 150px); text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } #heart { z-index: 8; } #echo { z-index: 7; } #heart::before, #heart::after, #echo::before, #echo::after { content: ''; position: absolute; top: 40px; width: 150px; height: 240px; background: #c66c75; border-radius: 150px 150px 0 0; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; transform-origin: 0 100%; } #heart::before, #echo::before { left: 150px; } #heart::after, #echo::after { left: 0; -webkit-transform: rotate(45deg); transform: rotate(45deg); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; } /* It needs some depth */ #heart::after { box-shadow: inset -6px -6px 0px 6px rgba(255,255,255,0.1); } #heart::before { box-shadow: inset 6px 6px 0px 6px rgba(255,255,255,0.1); } /* Makin it mine. */ #heart i::before { content: 'melon&luke'; position: absolute; z-index: 9; width: 100%; top: 35%; left: 0; font-style: normal; color: rgba(255,255,255,0.8); font-weight: 100; font-size: 30px; text-shadow: -1px -1px 0px rgba(0,0,0,0.2); } /* * Hearts gotta beat. */ @-webkit-keyframes heartbeat { 0%, 100% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { -webkit-transform: scale(1.00); transform: scale(1.00); } } @keyframes heartbeat { 0%, 100% { transform: scale(0.95); } 50% { transform: scale(1.00); } } @-webkit-keyframes echo { 0% { opacity: 0.1; -webkit-transform: scale(1); transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(1.4); transform: scale(1.4); } } @keyframes echo { 0% { opacity: 0.1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.4); } } /* * Beautiful! Now for the beating... */ #heart, #echo { -webkit-animation-duration: 2000ms; animation-duration: 2000ms; -webkit-animation-timing-function: cubic-bezier(0, 0, 0, 1.74); animation-timing-function: cubic-bezier(0, 0, 0, 1.74); -webkit-animation-delay: 500ms; animation-delay: 500ms; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-play-state: paused; animation-play-state: paused; } #heart { -webkit-animation-name: heartbeat; animation-name: heartbeat; } #echo { -webkit-animation-name: echo; animation-name: echo; } /* * Ready... */ #heart, #echo { /* * ...set... */ -webkit-animation-play-state: running; animation-play-state: running; /* * ...beat! */ } /* * * Wahoo! * * We did it! * * I mean *I* did it, but you know, whatever... * PI:NAME:<NAME>END_PI definitely did not have anything * to do with this. * * This pen loves CodePen! * * See you later! * */ """ openComment = false writeStyleChar = (which) -> # begin wrapping open comments if which == '/' && openComment == false openComment = true styles = $('#style-text').html() + which else if which == '/' && openComment == true openComment = false styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>') # wrap style declaration else if which == ':' styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:') # wrap style value else if which == ';' styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;') # wrap selector else if which == '{' styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{') else styles = $('#style-text').html() + which $('#style-text').html styles $('#style-tag').append which writeStyles = (message, index, interval) -> if index < message.length pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight writeStyleChar message[index++] setTimeout (-> writeStyles message, index, interval ), interval # appending the tags I'll need. $('body').append """ <style id="style-tag"></style> <span id="echo"></span> <span id="heart"><i></i></span> <pre id="style-text"></pre> """ # faster typing in small iframe on codepen homepage time = if window.innerWidth <= 578 then 4 else 16 # starting it off writeStyles(styles, 0, time) ### Changelog: 1.0.0: i exist! 1.0.1: heart instead of circle 1.0.2: including standard CSS3 transforms and animations was only using `-webkit` to be less verbose (standard transforms dont work in safari) now works in FF 1.0.3: crossbrowser echo nested `scale()` styles (scaled in scaled) only worked in chrome moved echo out of heart to fix 1.0.4: more efficient animations `0%, 100% {}` instead of duplicated keyframes ###
[ { "context": " this.arrow = paper.Path.Arrow\n name: \"spine\"\n arrowColor: \"purple\"\n arr", "end": 6679, "score": 0.8045692443847656, "start": 6674, "tag": "NAME", "value": "spine" }, { "context": " tensioner = new paper.Path.Circle\n name: \"tensioner\"\n position: sink_path.getPointAt(0", "end": 16837, "score": 0.5301699042320251, "start": 16836, "tag": "NAME", "value": "t" } ]
rails-material/app/assets/javascripts/canvas_ui/heater_magnet.coffee
The-Hybrid-Atelier/program-as-material
0
class window.HeaterMagnet extends UIElement name: "heater_magnet" strokeWidth: 10 strokeInterval: Ruler.mm2pts(0.5) styles: boundary_passive: (scope)-> heatColor = HeatSim.temperatureColor(scope.getRelationalResistance(), with_white=false, reverse=true) heatColor.alpha = 0.5 heatColorStroke = heatColor.clone() heatColorStroke.alpha = 1.0 style = fillColor: heatColor strokeColor: heatColorStroke strokeWidth: 4 closed: true strokeCap: "butt" strokeJoin: "round" miterLimit: 0 boundary_active: ()-> style = fillColor: null opacity: 1 strokeColor: "#DDDDDD" strokeWidth: 1 spine_active: ()-> style = visible: false spine_passive: ()-> style = visible: true source_active: ()-> style = visible: true strokeColor: "#DDDDDD" strokeWidth: 2 fillColor: "white" shadowColor: new paper.Color(0, 0, 0, 0.8) shadowBlur: 5 source_passive: ()-> style = visible: false source_motion: ()-> style = visible: true strokeColor: "#DDDDDD" strokeWidth: 4 fillColor: "white" sink_passive: ()-> style = visible: false sink_active: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) sw = (1 - scope.getRelationalResistance()) * 6 + 1 blue = new paper.Color "#00A8E1" blue.brightness = blue.brightness - 0.2 style = visible: true strokeColor: t strokeWidth: sw fillColor: blue shadowColor: new paper.Color(0, 0, 0, 0.8) shadowBlur: 5 sink_motion: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) sw = (1 - scope.getRelationalResistance()) * 6 + 1 style = visible: true strokeColor: t strokeWidth: sw fillColor: "#00A8E1" meter_active: ()-> style = fillColor: "#111111" visible: true meter_passive: ()-> style = visible: true tensioner_active: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) style = visible: true fillColor: t shadowColor: new paper.Color(0, 0, 0, 0.5) shadowBlur: 5 tensioner_passive: (scope)-> style = visible: false create: (options)-> heat_layer.activate() boundary = options.boundary boundary.name = "boundary" @setStyle boundary, "passive" @addComponents [boundary] this.hs = new HeatSpace properties: parent: b1 A: @area() area: ()-> boundary = @getComponent "boundary" area = Math.abs(boundary.area) area = Ruler.pts2mm(area) area = Ruler.pts2mm(area) return area update: ()-> @makeJouleHeater() heat_sim.update() @ui.bringToFront() boundary = @getComponent "boundary" console.log "AREA", @area() this.hs.A = @area() setStyle: (comp, c)-> if comp style = comp.name + "_" + c if @styles[style] comp.set @styles[style](this) setStyles: (c)-> scope = this comps = @getCollection("components") _.each comps, (cp)-> scope.setStyle(cp, c) activeMode: ()-> @deleteComponent "spool" @deleteComponent "meter" source = @getComponent "source" sink = @getComponent "sink" terminals_made = source and sink if not terminals_made then @make_terminals() @makeJouleHeater(true) @circuit_status() @boundary_interaction_active() @setStyles "active" @generateParallel() @RESOLUTION: 5 generateParallel: ()-> scope = this boundary = @getComponent "boundary" spine = @getComponent "spine" heat_layer.activate() if spine and boundary spine = spine.children.arrowbody extendSpine = (spine, boundary)-> spine = spine.clone() spine.visible = true spine.parent = heat_layer ## HEAD n2 = spine.getPointAt(spine.length-1) n1 = spine.getPointAt(spine.length-5) n = n2.subtract(n1) n.length = 1000000 spine.addSegment(n2.add(n)) ixts = spine.getIntersections(boundary) spine.lastSegment.point = ixts[0].point ## TAIL n2 = spine.getPointAt(0) n1 = spine.getPointAt(5) n = n2.subtract(n1) n.length = 1000000 spine.insertSegment(0, n2.add(n)) ixts = spine.getIntersections(boundary) spine.firstSegment.point = ixts[0].point return spine extractSubRegion = (r1, r2, spine, boundary)-> console.log "SR", r1, r2, spine.length p1 = spine.getPointAt(r1) p2 = spine.getPointAt(r2) norm1 = spine.getNormalAt(r1) norm2 = spine.getNormalAt(r2) norm1.length = 100 norm2.length = 100 rectangle = new paper.Path segments: [p1, p1.add(norm1), p2.add(norm2), p2, p2.subtract(norm2), p1.subtract(norm1)] closed: true region = boundary.intersect(rectangle) region.set fillColor: "orange" strokeColor: "purple" strokeWidth: 2 rectangle.remove() return region spine = extendSpine(spine, boundary) rails = _.range 0, spine.length + 1, spine.length / HeaterMagnet.RESOLUTION console.log "SPINE LENGTH", spine _.each rails, (r, i, arr)-> if i + 1 >= arr.length then return r1 = r r2 = _.min [arr[i + 1], spine.length] region = extractSubRegion(r1, r2, spine, boundary) h = new HeaterMagnet boundary: region h.update() scope.destroy() getMode: ()-> return if @getComponent "joule" then "active" else "passive" boundary_interaction_passive: ()-> scope = this boundary = @getComponent "boundary" boundary.fireTouchGestures() boundary.set onBrushStart: (e)-> scope.deleteComponent "spine" this.arrow = paper.Path.Arrow name: "spine" arrowColor: "purple" arrowWidth: 6 arrowHead: "solid" headScale: 0.6 onMouseDown: (e)-> scope.deleteComponent "spine" this.remove() this.arrow.addPoint(e.point) scope.addComponent this.arrow onBrushDrag: (e)-> if this.arrow this.arrow.addPoint(e.point) onBrushEnd: (e)-> onBrushTap: (e)-> scope.activeMode() boundary_interaction_active: ()-> scope = this boundary = @getComponent "boundary" boundary.fireTouchGestures() boundary.set onBrushStart: (e)-> console.log "Active boundary md" onBrushDrag: (e)-> onBrushEnd: (e)-> onBrushTap: (e)-> scope.activeMode() passiveMode: ()-> # REMOVE ELEMENTS @deleteComponent "resistance_ui" @deleteComponent "meter" @deleteComponent "joule" @deleteComponent "spool" # LOCAL COMPONENTS boundary = @getComponent "boundary" ui_layer.activate() meter = new PointText name: "meter" content: @getResistance() fillColor: 'black' fontFamily: 'Avenir' fontWeight: 'bold' fontSize: 15 meter.set pivot: meter.bounds.center position: boundary.bounds.center.clone() @addComponent meter @boundary_interaction_passive() s = new Spool properties: color: new paper.Color("#21BA45") scale: 4 s.position = boundary.bounds.topLeft.clone() s.connection = boundary.getNearestPoint(s._ui.position) s.fill = @getRelationalResistance() @addComponent s._ui # PASSIVE STYLE @setStyles "passive" interaction: ()-> scope = this if @getMode() == "active" @boundary_interaction_active() else @boundary_interaction_passive() @joule_interaction() @terminal_interaction() @tensioner_interaction() tensioner_interaction: ()-> scope = this sink = @getComponent "sink" if sink sink_path = sink.self.getComponent "magnet_component" tensioner = @getComponent "tensioner" if tensioner tensioner.set dtheta: 0 last_point: null min: Ruler.mm2pts(0.3) max: Ruler.mm2pts(10) onMouseDown: (e)-> this.sw = scope.strokeWidth this.dtheta = 0 this.last_point = null Magnet.hide() playSound("Tiny-Glitch") onMouseDrag: (e)-> this.position = sink_path.getNearestPoint this.position.add(e.delta) if this.last_point center = sink_path.bounds.center.clone() a = this.last_point.subtract(center) b = this.position.subtract(center) this.dtheta = this.dtheta + a.getDirectedAngle(b) this.last_point = this.position.clone() this.steps = this.dtheta / 180 sw = this.sw sw = sw + (this.steps * 0.3) if sw > this.max sw = this.max if sw < this.min sw = this.min scope.strokeWidth = sw scope.setStyle this, "active" scope.setStyle sink, "active" scope.update() onMouseUp: (e)-> playSound("Tiny-Glitch") joule_interaction: ()-> scope = this joule = @getComponent "joule" if joule joule.fireTouchGestures() joule.set onBrushTap: ()-> scope.passiveMode() terminal_interaction: ()-> scope = this ui = @ui boundary = @getComponent "boundary" source = @getComponent "source" sink = @getComponent "sink" if source and sink _.each [source, sink], (terminal)-> # SEE NOTEBOOK.COFFEE terminal.fireTouchGestures() terminal.set getBoundaryPosition: (point)-> point = boundary.getNearestPoint(point) offset = boundary.getOffsetOf(point) normal = boundary.getNormalAt(offset) normal.length = -15 return point.clone().add(normal) # BRUSH GESTURE onBrushTap: (e)-> Magnet.hide() scope.update() onBrushStart: (e)-> Magnet.hide() tensioner = scope.getComponent "tensioner" if tensioner tensioner.visible = false this.m_down(e) sink = scope.getComponent "sink" scope.setStyles "motion" this.position = this.getBoundaryPosition(this.position) scope.update() onBrushDrag: (e)-> this.m_drag(e) this.position = this.getBoundaryPosition(this.position) scope.update() onBrushEnd: (e)-> tensioner = scope.getComponent "tensioner" sink = scope.getComponent "sink" this.m_up(e) scope.setStyles "active" this.position = this.getBoundaryPosition(this.position) scope.setStyle sink, "active" if tensioner tensioner.position = sink.children.magnet_component.getPointAt(0) tensioner.visible = true scope.update() # HOLD GESTURE onHoldTap: (e)-> console.log "brush tap" onHoldStart: (e)-> this.strokeWidth = 2 console.log "brush start" this.line_magnet = new LineMagnet layer: circuit_layer point: e.point if this.name == "source" magnet = this.line_magnet.getComponent("end_terminal") else magnet = this.line_magnet.getComponent("start_terminal") magnet.self.addConnection(terminal) terminal.self.getUIElement().update() magnet.position = terminal.position scope.update() onHoldDrag: (e)-> console.log "brush drag" if this.name == "source" this.line_magnet.setStartTrace(e.point) else this.line_magnet.setEndTrace(e.point) ui.bringToFront() scope.update() onHoldEnd: (e)-> console.log "brush end" ui.bringToFront() scope.update() # this.line_magnet.setEndTrace(e.point) circuit_status: ()-> boundary = @getComponent "boundary" source = @getComponent "source" @deleteComponent "resistance_ui" @deleteComponent "meter" pt = boundary.getNearestPoint(boundary.bounds.topRight) offset = new paper.Point(0, 0) offset.angle = -45 offset.length = 60 right_offset = new paper.Point(0, 0) right_offset.angle = 0 right_offset.length = 30 ui_layer.activate() meter = new PointText name: "meter" content: @getResistance() fillColor: 'black' fontFamily: 'Avenir' fontWeight: 'bold' fontSize: 12 meter.pivot = meter.bounds.center meter.position = source.position # sWControl = @generateControlUI "strokeWidth", # position: meter.bounds.rightCenter.clone().add(right_offset) # min: Ruler.mm2pts(0.3) # max: Ruler.mm2pts(10) # padding: 30 # right_offset.length = right_offset.length # + sWControl.bounds.width # sIControl = @generateControlUI "strokeInterval", # position: meter.bounds.rightCenter.clone().add(right_offset) # min: Ruler.mm2pts(0.3) # max: Ruler.mm2pts(10) # padding: 30 resistance_ui = new paper.Group name: "resistance_ui" children: [meter] data: printable: false @addComponent resistance_ui # GEOMETRY GENERATION FUNCTIONS makeJouleHeater: (update=false)-> source = @getComponent "source" sink = @getComponent "sink" joule = @getComponent "joule" boundary = @getComponent "boundary" render_heater = source and sink if render_heater or update if joule then @deleteComponent "joule" params = boundaries: [boundary] source: source.position sink: sink.position joule = @serpentine params @joule_interaction() boundary.sendToBack() @circuit_status() make_terminals: ()-> boundary = @getComponent "boundary" params = boundaries: [boundary] source: boundary.getNearestPoint(boundary.bounds.topCenter) sink: boundary.getNearestPoint(boundary.bounds.bottomCenter) source_normal = boundary.getNormalAt(boundary.getOffsetOf(params.source)) sink_normal = boundary.getNormalAt(boundary.getOffsetOf(params.sink)) source_normal.length = -15 sink_normal.length = -15 source = new Magnet name: "source" magnets: ["C"] accepts: ["magnet_start_terminal", "magnet_end_terminal"] path: new paper.Path.Rectangle size: [60, 30] radius: 5 magnetClass: "magnet_sink" position: params.source.clone().add(source_normal) style: @styles.source_active() # source_handle = new paper.Path.Circle # radius: sink = new Magnet name: "sink" magnets: ["C"] accepts: ["magnet_start_terminal", "magnet_end_terminal"] path: new paper.Path.Circle magnetClass: "magnet_sink" radius: 15 position: params.sink.clone().add(sink_normal) style: @styles.sink_active(this) sink_path = sink.getComponent "magnet_component" tensioner = new paper.Path.Circle name: "tensioner" position: sink_path.getPointAt(0) radius: 10 @setStyle tensioner, "active" @addComponents [source.ui, sink.ui, tensioner] tensioner.bringToFront() @tensioner_interaction() @terminal_interaction() serpentine: (options)-> options.strokeWidth = this.strokeWidth options.strokeInterval = this.strokeInterval options.heatColor = this.getRelationalColor() scope = this boundary = options.boundaries[0] axis_length = Math.abs(options.source.subtract(options.sink).length) if axis_length < 30 @setStyle boundary, "passive" return else heat_layer.activate() joule = HeatSketch.snake options if joule @setStyle boundary, "active" @deleteComponent "joule" @addComponent joule joule.sendToBack() else @deleteComponent "joule" return joule generateControlUI: (field, config)-> scope = this ui_layer.activate() group = new paper.Group name: "control_"+field text = new PointText name: field parent: group fillColor: 'black' fontFamily: 'Avenir' fontSize: 15 content: Ruler.pts2mm(this[field]).toFixed(1) + " mm" data: value: this[field] # console.log text.bounds.topCenter.add(0, -config.padding) increase = new paper.Path.Circle parent: group name: "increase_"+field radius: 15 fillColor: "black" position: text.bounds.topCenter.add(0, -config.padding) onMouseDown: ()-> val = text.data.value val = val + 0.3 if val > config.max val = config.max text.data.value = val text.content = Ruler.pts2mm(val).toFixed(1) + " mm" scope[field] = val scope.update() decrease = new paper.Path.Circle parent: group name: "decrease_"+field radius: 15 fillColor: "red" position: text.bounds.bottomCenter.add(0, config.padding) onMouseDown: ()-> val = text.data.value val = val - 0.3 if val <= config.min val = config.min text.data.value = val text.content = Ruler.pts2mm(val).toFixed(1) + " mm" scope[field] = val scope.update() group.position = config.position return group # CIRCUIT ANALYSIS last_resistance_str: "- Ω" last_resistance: 0 getResistance: (string = true)-> joule = @getComponent "joule" if not joule rtn = if string then this.last_resistance_str else this.last_resistance return rtn length = Ruler.pts2mm(joule.length) cross_sectional = MaterialLib.AgIC.thickness * Ruler.pts2mm(joule.strokeWidth) resistance = MaterialLib.AgIC.resistivity * (length / cross_sectional) this.last_resistance_str = resistance.toFixed(0) + "Ω" this.last_resistance = resistance rtn = if string then this.last_resistance_str else this.last_resistance return rtn getRelationalResistance: ()-> p = @getResistance(false)/500 if p > 1 return 1 else if p < 0 return 0 else return p getRelationalColor: ()-> c = HeatSim.temperatureColor(@getRelationalResistance(),with_white=false, reverse=true) return c
136881
class window.HeaterMagnet extends UIElement name: "heater_magnet" strokeWidth: 10 strokeInterval: Ruler.mm2pts(0.5) styles: boundary_passive: (scope)-> heatColor = HeatSim.temperatureColor(scope.getRelationalResistance(), with_white=false, reverse=true) heatColor.alpha = 0.5 heatColorStroke = heatColor.clone() heatColorStroke.alpha = 1.0 style = fillColor: heatColor strokeColor: heatColorStroke strokeWidth: 4 closed: true strokeCap: "butt" strokeJoin: "round" miterLimit: 0 boundary_active: ()-> style = fillColor: null opacity: 1 strokeColor: "#DDDDDD" strokeWidth: 1 spine_active: ()-> style = visible: false spine_passive: ()-> style = visible: true source_active: ()-> style = visible: true strokeColor: "#DDDDDD" strokeWidth: 2 fillColor: "white" shadowColor: new paper.Color(0, 0, 0, 0.8) shadowBlur: 5 source_passive: ()-> style = visible: false source_motion: ()-> style = visible: true strokeColor: "#DDDDDD" strokeWidth: 4 fillColor: "white" sink_passive: ()-> style = visible: false sink_active: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) sw = (1 - scope.getRelationalResistance()) * 6 + 1 blue = new paper.Color "#00A8E1" blue.brightness = blue.brightness - 0.2 style = visible: true strokeColor: t strokeWidth: sw fillColor: blue shadowColor: new paper.Color(0, 0, 0, 0.8) shadowBlur: 5 sink_motion: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) sw = (1 - scope.getRelationalResistance()) * 6 + 1 style = visible: true strokeColor: t strokeWidth: sw fillColor: "#00A8E1" meter_active: ()-> style = fillColor: "#111111" visible: true meter_passive: ()-> style = visible: true tensioner_active: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) style = visible: true fillColor: t shadowColor: new paper.Color(0, 0, 0, 0.5) shadowBlur: 5 tensioner_passive: (scope)-> style = visible: false create: (options)-> heat_layer.activate() boundary = options.boundary boundary.name = "boundary" @setStyle boundary, "passive" @addComponents [boundary] this.hs = new HeatSpace properties: parent: b1 A: @area() area: ()-> boundary = @getComponent "boundary" area = Math.abs(boundary.area) area = Ruler.pts2mm(area) area = Ruler.pts2mm(area) return area update: ()-> @makeJouleHeater() heat_sim.update() @ui.bringToFront() boundary = @getComponent "boundary" console.log "AREA", @area() this.hs.A = @area() setStyle: (comp, c)-> if comp style = comp.name + "_" + c if @styles[style] comp.set @styles[style](this) setStyles: (c)-> scope = this comps = @getCollection("components") _.each comps, (cp)-> scope.setStyle(cp, c) activeMode: ()-> @deleteComponent "spool" @deleteComponent "meter" source = @getComponent "source" sink = @getComponent "sink" terminals_made = source and sink if not terminals_made then @make_terminals() @makeJouleHeater(true) @circuit_status() @boundary_interaction_active() @setStyles "active" @generateParallel() @RESOLUTION: 5 generateParallel: ()-> scope = this boundary = @getComponent "boundary" spine = @getComponent "spine" heat_layer.activate() if spine and boundary spine = spine.children.arrowbody extendSpine = (spine, boundary)-> spine = spine.clone() spine.visible = true spine.parent = heat_layer ## HEAD n2 = spine.getPointAt(spine.length-1) n1 = spine.getPointAt(spine.length-5) n = n2.subtract(n1) n.length = 1000000 spine.addSegment(n2.add(n)) ixts = spine.getIntersections(boundary) spine.lastSegment.point = ixts[0].point ## TAIL n2 = spine.getPointAt(0) n1 = spine.getPointAt(5) n = n2.subtract(n1) n.length = 1000000 spine.insertSegment(0, n2.add(n)) ixts = spine.getIntersections(boundary) spine.firstSegment.point = ixts[0].point return spine extractSubRegion = (r1, r2, spine, boundary)-> console.log "SR", r1, r2, spine.length p1 = spine.getPointAt(r1) p2 = spine.getPointAt(r2) norm1 = spine.getNormalAt(r1) norm2 = spine.getNormalAt(r2) norm1.length = 100 norm2.length = 100 rectangle = new paper.Path segments: [p1, p1.add(norm1), p2.add(norm2), p2, p2.subtract(norm2), p1.subtract(norm1)] closed: true region = boundary.intersect(rectangle) region.set fillColor: "orange" strokeColor: "purple" strokeWidth: 2 rectangle.remove() return region spine = extendSpine(spine, boundary) rails = _.range 0, spine.length + 1, spine.length / HeaterMagnet.RESOLUTION console.log "SPINE LENGTH", spine _.each rails, (r, i, arr)-> if i + 1 >= arr.length then return r1 = r r2 = _.min [arr[i + 1], spine.length] region = extractSubRegion(r1, r2, spine, boundary) h = new HeaterMagnet boundary: region h.update() scope.destroy() getMode: ()-> return if @getComponent "joule" then "active" else "passive" boundary_interaction_passive: ()-> scope = this boundary = @getComponent "boundary" boundary.fireTouchGestures() boundary.set onBrushStart: (e)-> scope.deleteComponent "spine" this.arrow = paper.Path.Arrow name: "<NAME>" arrowColor: "purple" arrowWidth: 6 arrowHead: "solid" headScale: 0.6 onMouseDown: (e)-> scope.deleteComponent "spine" this.remove() this.arrow.addPoint(e.point) scope.addComponent this.arrow onBrushDrag: (e)-> if this.arrow this.arrow.addPoint(e.point) onBrushEnd: (e)-> onBrushTap: (e)-> scope.activeMode() boundary_interaction_active: ()-> scope = this boundary = @getComponent "boundary" boundary.fireTouchGestures() boundary.set onBrushStart: (e)-> console.log "Active boundary md" onBrushDrag: (e)-> onBrushEnd: (e)-> onBrushTap: (e)-> scope.activeMode() passiveMode: ()-> # REMOVE ELEMENTS @deleteComponent "resistance_ui" @deleteComponent "meter" @deleteComponent "joule" @deleteComponent "spool" # LOCAL COMPONENTS boundary = @getComponent "boundary" ui_layer.activate() meter = new PointText name: "meter" content: @getResistance() fillColor: 'black' fontFamily: 'Avenir' fontWeight: 'bold' fontSize: 15 meter.set pivot: meter.bounds.center position: boundary.bounds.center.clone() @addComponent meter @boundary_interaction_passive() s = new Spool properties: color: new paper.Color("#21BA45") scale: 4 s.position = boundary.bounds.topLeft.clone() s.connection = boundary.getNearestPoint(s._ui.position) s.fill = @getRelationalResistance() @addComponent s._ui # PASSIVE STYLE @setStyles "passive" interaction: ()-> scope = this if @getMode() == "active" @boundary_interaction_active() else @boundary_interaction_passive() @joule_interaction() @terminal_interaction() @tensioner_interaction() tensioner_interaction: ()-> scope = this sink = @getComponent "sink" if sink sink_path = sink.self.getComponent "magnet_component" tensioner = @getComponent "tensioner" if tensioner tensioner.set dtheta: 0 last_point: null min: Ruler.mm2pts(0.3) max: Ruler.mm2pts(10) onMouseDown: (e)-> this.sw = scope.strokeWidth this.dtheta = 0 this.last_point = null Magnet.hide() playSound("Tiny-Glitch") onMouseDrag: (e)-> this.position = sink_path.getNearestPoint this.position.add(e.delta) if this.last_point center = sink_path.bounds.center.clone() a = this.last_point.subtract(center) b = this.position.subtract(center) this.dtheta = this.dtheta + a.getDirectedAngle(b) this.last_point = this.position.clone() this.steps = this.dtheta / 180 sw = this.sw sw = sw + (this.steps * 0.3) if sw > this.max sw = this.max if sw < this.min sw = this.min scope.strokeWidth = sw scope.setStyle this, "active" scope.setStyle sink, "active" scope.update() onMouseUp: (e)-> playSound("Tiny-Glitch") joule_interaction: ()-> scope = this joule = @getComponent "joule" if joule joule.fireTouchGestures() joule.set onBrushTap: ()-> scope.passiveMode() terminal_interaction: ()-> scope = this ui = @ui boundary = @getComponent "boundary" source = @getComponent "source" sink = @getComponent "sink" if source and sink _.each [source, sink], (terminal)-> # SEE NOTEBOOK.COFFEE terminal.fireTouchGestures() terminal.set getBoundaryPosition: (point)-> point = boundary.getNearestPoint(point) offset = boundary.getOffsetOf(point) normal = boundary.getNormalAt(offset) normal.length = -15 return point.clone().add(normal) # BRUSH GESTURE onBrushTap: (e)-> Magnet.hide() scope.update() onBrushStart: (e)-> Magnet.hide() tensioner = scope.getComponent "tensioner" if tensioner tensioner.visible = false this.m_down(e) sink = scope.getComponent "sink" scope.setStyles "motion" this.position = this.getBoundaryPosition(this.position) scope.update() onBrushDrag: (e)-> this.m_drag(e) this.position = this.getBoundaryPosition(this.position) scope.update() onBrushEnd: (e)-> tensioner = scope.getComponent "tensioner" sink = scope.getComponent "sink" this.m_up(e) scope.setStyles "active" this.position = this.getBoundaryPosition(this.position) scope.setStyle sink, "active" if tensioner tensioner.position = sink.children.magnet_component.getPointAt(0) tensioner.visible = true scope.update() # HOLD GESTURE onHoldTap: (e)-> console.log "brush tap" onHoldStart: (e)-> this.strokeWidth = 2 console.log "brush start" this.line_magnet = new LineMagnet layer: circuit_layer point: e.point if this.name == "source" magnet = this.line_magnet.getComponent("end_terminal") else magnet = this.line_magnet.getComponent("start_terminal") magnet.self.addConnection(terminal) terminal.self.getUIElement().update() magnet.position = terminal.position scope.update() onHoldDrag: (e)-> console.log "brush drag" if this.name == "source" this.line_magnet.setStartTrace(e.point) else this.line_magnet.setEndTrace(e.point) ui.bringToFront() scope.update() onHoldEnd: (e)-> console.log "brush end" ui.bringToFront() scope.update() # this.line_magnet.setEndTrace(e.point) circuit_status: ()-> boundary = @getComponent "boundary" source = @getComponent "source" @deleteComponent "resistance_ui" @deleteComponent "meter" pt = boundary.getNearestPoint(boundary.bounds.topRight) offset = new paper.Point(0, 0) offset.angle = -45 offset.length = 60 right_offset = new paper.Point(0, 0) right_offset.angle = 0 right_offset.length = 30 ui_layer.activate() meter = new PointText name: "meter" content: @getResistance() fillColor: 'black' fontFamily: 'Avenir' fontWeight: 'bold' fontSize: 12 meter.pivot = meter.bounds.center meter.position = source.position # sWControl = @generateControlUI "strokeWidth", # position: meter.bounds.rightCenter.clone().add(right_offset) # min: Ruler.mm2pts(0.3) # max: Ruler.mm2pts(10) # padding: 30 # right_offset.length = right_offset.length # + sWControl.bounds.width # sIControl = @generateControlUI "strokeInterval", # position: meter.bounds.rightCenter.clone().add(right_offset) # min: Ruler.mm2pts(0.3) # max: Ruler.mm2pts(10) # padding: 30 resistance_ui = new paper.Group name: "resistance_ui" children: [meter] data: printable: false @addComponent resistance_ui # GEOMETRY GENERATION FUNCTIONS makeJouleHeater: (update=false)-> source = @getComponent "source" sink = @getComponent "sink" joule = @getComponent "joule" boundary = @getComponent "boundary" render_heater = source and sink if render_heater or update if joule then @deleteComponent "joule" params = boundaries: [boundary] source: source.position sink: sink.position joule = @serpentine params @joule_interaction() boundary.sendToBack() @circuit_status() make_terminals: ()-> boundary = @getComponent "boundary" params = boundaries: [boundary] source: boundary.getNearestPoint(boundary.bounds.topCenter) sink: boundary.getNearestPoint(boundary.bounds.bottomCenter) source_normal = boundary.getNormalAt(boundary.getOffsetOf(params.source)) sink_normal = boundary.getNormalAt(boundary.getOffsetOf(params.sink)) source_normal.length = -15 sink_normal.length = -15 source = new Magnet name: "source" magnets: ["C"] accepts: ["magnet_start_terminal", "magnet_end_terminal"] path: new paper.Path.Rectangle size: [60, 30] radius: 5 magnetClass: "magnet_sink" position: params.source.clone().add(source_normal) style: @styles.source_active() # source_handle = new paper.Path.Circle # radius: sink = new Magnet name: "sink" magnets: ["C"] accepts: ["magnet_start_terminal", "magnet_end_terminal"] path: new paper.Path.Circle magnetClass: "magnet_sink" radius: 15 position: params.sink.clone().add(sink_normal) style: @styles.sink_active(this) sink_path = sink.getComponent "magnet_component" tensioner = new paper.Path.Circle name: "<NAME>ensioner" position: sink_path.getPointAt(0) radius: 10 @setStyle tensioner, "active" @addComponents [source.ui, sink.ui, tensioner] tensioner.bringToFront() @tensioner_interaction() @terminal_interaction() serpentine: (options)-> options.strokeWidth = this.strokeWidth options.strokeInterval = this.strokeInterval options.heatColor = this.getRelationalColor() scope = this boundary = options.boundaries[0] axis_length = Math.abs(options.source.subtract(options.sink).length) if axis_length < 30 @setStyle boundary, "passive" return else heat_layer.activate() joule = HeatSketch.snake options if joule @setStyle boundary, "active" @deleteComponent "joule" @addComponent joule joule.sendToBack() else @deleteComponent "joule" return joule generateControlUI: (field, config)-> scope = this ui_layer.activate() group = new paper.Group name: "control_"+field text = new PointText name: field parent: group fillColor: 'black' fontFamily: 'Avenir' fontSize: 15 content: Ruler.pts2mm(this[field]).toFixed(1) + " mm" data: value: this[field] # console.log text.bounds.topCenter.add(0, -config.padding) increase = new paper.Path.Circle parent: group name: "increase_"+field radius: 15 fillColor: "black" position: text.bounds.topCenter.add(0, -config.padding) onMouseDown: ()-> val = text.data.value val = val + 0.3 if val > config.max val = config.max text.data.value = val text.content = Ruler.pts2mm(val).toFixed(1) + " mm" scope[field] = val scope.update() decrease = new paper.Path.Circle parent: group name: "decrease_"+field radius: 15 fillColor: "red" position: text.bounds.bottomCenter.add(0, config.padding) onMouseDown: ()-> val = text.data.value val = val - 0.3 if val <= config.min val = config.min text.data.value = val text.content = Ruler.pts2mm(val).toFixed(1) + " mm" scope[field] = val scope.update() group.position = config.position return group # CIRCUIT ANALYSIS last_resistance_str: "- Ω" last_resistance: 0 getResistance: (string = true)-> joule = @getComponent "joule" if not joule rtn = if string then this.last_resistance_str else this.last_resistance return rtn length = Ruler.pts2mm(joule.length) cross_sectional = MaterialLib.AgIC.thickness * Ruler.pts2mm(joule.strokeWidth) resistance = MaterialLib.AgIC.resistivity * (length / cross_sectional) this.last_resistance_str = resistance.toFixed(0) + "Ω" this.last_resistance = resistance rtn = if string then this.last_resistance_str else this.last_resistance return rtn getRelationalResistance: ()-> p = @getResistance(false)/500 if p > 1 return 1 else if p < 0 return 0 else return p getRelationalColor: ()-> c = HeatSim.temperatureColor(@getRelationalResistance(),with_white=false, reverse=true) return c
true
class window.HeaterMagnet extends UIElement name: "heater_magnet" strokeWidth: 10 strokeInterval: Ruler.mm2pts(0.5) styles: boundary_passive: (scope)-> heatColor = HeatSim.temperatureColor(scope.getRelationalResistance(), with_white=false, reverse=true) heatColor.alpha = 0.5 heatColorStroke = heatColor.clone() heatColorStroke.alpha = 1.0 style = fillColor: heatColor strokeColor: heatColorStroke strokeWidth: 4 closed: true strokeCap: "butt" strokeJoin: "round" miterLimit: 0 boundary_active: ()-> style = fillColor: null opacity: 1 strokeColor: "#DDDDDD" strokeWidth: 1 spine_active: ()-> style = visible: false spine_passive: ()-> style = visible: true source_active: ()-> style = visible: true strokeColor: "#DDDDDD" strokeWidth: 2 fillColor: "white" shadowColor: new paper.Color(0, 0, 0, 0.8) shadowBlur: 5 source_passive: ()-> style = visible: false source_motion: ()-> style = visible: true strokeColor: "#DDDDDD" strokeWidth: 4 fillColor: "white" sink_passive: ()-> style = visible: false sink_active: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) sw = (1 - scope.getRelationalResistance()) * 6 + 1 blue = new paper.Color "#00A8E1" blue.brightness = blue.brightness - 0.2 style = visible: true strokeColor: t strokeWidth: sw fillColor: blue shadowColor: new paper.Color(0, 0, 0, 0.8) shadowBlur: 5 sink_motion: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) sw = (1 - scope.getRelationalResistance()) * 6 + 1 style = visible: true strokeColor: t strokeWidth: sw fillColor: "#00A8E1" meter_active: ()-> style = fillColor: "#111111" visible: true meter_passive: ()-> style = visible: true tensioner_active: (scope)-> t = HeatSim.temperatureColor(scope.getRelationalResistance(),with_white=false, reverse=true) style = visible: true fillColor: t shadowColor: new paper.Color(0, 0, 0, 0.5) shadowBlur: 5 tensioner_passive: (scope)-> style = visible: false create: (options)-> heat_layer.activate() boundary = options.boundary boundary.name = "boundary" @setStyle boundary, "passive" @addComponents [boundary] this.hs = new HeatSpace properties: parent: b1 A: @area() area: ()-> boundary = @getComponent "boundary" area = Math.abs(boundary.area) area = Ruler.pts2mm(area) area = Ruler.pts2mm(area) return area update: ()-> @makeJouleHeater() heat_sim.update() @ui.bringToFront() boundary = @getComponent "boundary" console.log "AREA", @area() this.hs.A = @area() setStyle: (comp, c)-> if comp style = comp.name + "_" + c if @styles[style] comp.set @styles[style](this) setStyles: (c)-> scope = this comps = @getCollection("components") _.each comps, (cp)-> scope.setStyle(cp, c) activeMode: ()-> @deleteComponent "spool" @deleteComponent "meter" source = @getComponent "source" sink = @getComponent "sink" terminals_made = source and sink if not terminals_made then @make_terminals() @makeJouleHeater(true) @circuit_status() @boundary_interaction_active() @setStyles "active" @generateParallel() @RESOLUTION: 5 generateParallel: ()-> scope = this boundary = @getComponent "boundary" spine = @getComponent "spine" heat_layer.activate() if spine and boundary spine = spine.children.arrowbody extendSpine = (spine, boundary)-> spine = spine.clone() spine.visible = true spine.parent = heat_layer ## HEAD n2 = spine.getPointAt(spine.length-1) n1 = spine.getPointAt(spine.length-5) n = n2.subtract(n1) n.length = 1000000 spine.addSegment(n2.add(n)) ixts = spine.getIntersections(boundary) spine.lastSegment.point = ixts[0].point ## TAIL n2 = spine.getPointAt(0) n1 = spine.getPointAt(5) n = n2.subtract(n1) n.length = 1000000 spine.insertSegment(0, n2.add(n)) ixts = spine.getIntersections(boundary) spine.firstSegment.point = ixts[0].point return spine extractSubRegion = (r1, r2, spine, boundary)-> console.log "SR", r1, r2, spine.length p1 = spine.getPointAt(r1) p2 = spine.getPointAt(r2) norm1 = spine.getNormalAt(r1) norm2 = spine.getNormalAt(r2) norm1.length = 100 norm2.length = 100 rectangle = new paper.Path segments: [p1, p1.add(norm1), p2.add(norm2), p2, p2.subtract(norm2), p1.subtract(norm1)] closed: true region = boundary.intersect(rectangle) region.set fillColor: "orange" strokeColor: "purple" strokeWidth: 2 rectangle.remove() return region spine = extendSpine(spine, boundary) rails = _.range 0, spine.length + 1, spine.length / HeaterMagnet.RESOLUTION console.log "SPINE LENGTH", spine _.each rails, (r, i, arr)-> if i + 1 >= arr.length then return r1 = r r2 = _.min [arr[i + 1], spine.length] region = extractSubRegion(r1, r2, spine, boundary) h = new HeaterMagnet boundary: region h.update() scope.destroy() getMode: ()-> return if @getComponent "joule" then "active" else "passive" boundary_interaction_passive: ()-> scope = this boundary = @getComponent "boundary" boundary.fireTouchGestures() boundary.set onBrushStart: (e)-> scope.deleteComponent "spine" this.arrow = paper.Path.Arrow name: "PI:NAME:<NAME>END_PI" arrowColor: "purple" arrowWidth: 6 arrowHead: "solid" headScale: 0.6 onMouseDown: (e)-> scope.deleteComponent "spine" this.remove() this.arrow.addPoint(e.point) scope.addComponent this.arrow onBrushDrag: (e)-> if this.arrow this.arrow.addPoint(e.point) onBrushEnd: (e)-> onBrushTap: (e)-> scope.activeMode() boundary_interaction_active: ()-> scope = this boundary = @getComponent "boundary" boundary.fireTouchGestures() boundary.set onBrushStart: (e)-> console.log "Active boundary md" onBrushDrag: (e)-> onBrushEnd: (e)-> onBrushTap: (e)-> scope.activeMode() passiveMode: ()-> # REMOVE ELEMENTS @deleteComponent "resistance_ui" @deleteComponent "meter" @deleteComponent "joule" @deleteComponent "spool" # LOCAL COMPONENTS boundary = @getComponent "boundary" ui_layer.activate() meter = new PointText name: "meter" content: @getResistance() fillColor: 'black' fontFamily: 'Avenir' fontWeight: 'bold' fontSize: 15 meter.set pivot: meter.bounds.center position: boundary.bounds.center.clone() @addComponent meter @boundary_interaction_passive() s = new Spool properties: color: new paper.Color("#21BA45") scale: 4 s.position = boundary.bounds.topLeft.clone() s.connection = boundary.getNearestPoint(s._ui.position) s.fill = @getRelationalResistance() @addComponent s._ui # PASSIVE STYLE @setStyles "passive" interaction: ()-> scope = this if @getMode() == "active" @boundary_interaction_active() else @boundary_interaction_passive() @joule_interaction() @terminal_interaction() @tensioner_interaction() tensioner_interaction: ()-> scope = this sink = @getComponent "sink" if sink sink_path = sink.self.getComponent "magnet_component" tensioner = @getComponent "tensioner" if tensioner tensioner.set dtheta: 0 last_point: null min: Ruler.mm2pts(0.3) max: Ruler.mm2pts(10) onMouseDown: (e)-> this.sw = scope.strokeWidth this.dtheta = 0 this.last_point = null Magnet.hide() playSound("Tiny-Glitch") onMouseDrag: (e)-> this.position = sink_path.getNearestPoint this.position.add(e.delta) if this.last_point center = sink_path.bounds.center.clone() a = this.last_point.subtract(center) b = this.position.subtract(center) this.dtheta = this.dtheta + a.getDirectedAngle(b) this.last_point = this.position.clone() this.steps = this.dtheta / 180 sw = this.sw sw = sw + (this.steps * 0.3) if sw > this.max sw = this.max if sw < this.min sw = this.min scope.strokeWidth = sw scope.setStyle this, "active" scope.setStyle sink, "active" scope.update() onMouseUp: (e)-> playSound("Tiny-Glitch") joule_interaction: ()-> scope = this joule = @getComponent "joule" if joule joule.fireTouchGestures() joule.set onBrushTap: ()-> scope.passiveMode() terminal_interaction: ()-> scope = this ui = @ui boundary = @getComponent "boundary" source = @getComponent "source" sink = @getComponent "sink" if source and sink _.each [source, sink], (terminal)-> # SEE NOTEBOOK.COFFEE terminal.fireTouchGestures() terminal.set getBoundaryPosition: (point)-> point = boundary.getNearestPoint(point) offset = boundary.getOffsetOf(point) normal = boundary.getNormalAt(offset) normal.length = -15 return point.clone().add(normal) # BRUSH GESTURE onBrushTap: (e)-> Magnet.hide() scope.update() onBrushStart: (e)-> Magnet.hide() tensioner = scope.getComponent "tensioner" if tensioner tensioner.visible = false this.m_down(e) sink = scope.getComponent "sink" scope.setStyles "motion" this.position = this.getBoundaryPosition(this.position) scope.update() onBrushDrag: (e)-> this.m_drag(e) this.position = this.getBoundaryPosition(this.position) scope.update() onBrushEnd: (e)-> tensioner = scope.getComponent "tensioner" sink = scope.getComponent "sink" this.m_up(e) scope.setStyles "active" this.position = this.getBoundaryPosition(this.position) scope.setStyle sink, "active" if tensioner tensioner.position = sink.children.magnet_component.getPointAt(0) tensioner.visible = true scope.update() # HOLD GESTURE onHoldTap: (e)-> console.log "brush tap" onHoldStart: (e)-> this.strokeWidth = 2 console.log "brush start" this.line_magnet = new LineMagnet layer: circuit_layer point: e.point if this.name == "source" magnet = this.line_magnet.getComponent("end_terminal") else magnet = this.line_magnet.getComponent("start_terminal") magnet.self.addConnection(terminal) terminal.self.getUIElement().update() magnet.position = terminal.position scope.update() onHoldDrag: (e)-> console.log "brush drag" if this.name == "source" this.line_magnet.setStartTrace(e.point) else this.line_magnet.setEndTrace(e.point) ui.bringToFront() scope.update() onHoldEnd: (e)-> console.log "brush end" ui.bringToFront() scope.update() # this.line_magnet.setEndTrace(e.point) circuit_status: ()-> boundary = @getComponent "boundary" source = @getComponent "source" @deleteComponent "resistance_ui" @deleteComponent "meter" pt = boundary.getNearestPoint(boundary.bounds.topRight) offset = new paper.Point(0, 0) offset.angle = -45 offset.length = 60 right_offset = new paper.Point(0, 0) right_offset.angle = 0 right_offset.length = 30 ui_layer.activate() meter = new PointText name: "meter" content: @getResistance() fillColor: 'black' fontFamily: 'Avenir' fontWeight: 'bold' fontSize: 12 meter.pivot = meter.bounds.center meter.position = source.position # sWControl = @generateControlUI "strokeWidth", # position: meter.bounds.rightCenter.clone().add(right_offset) # min: Ruler.mm2pts(0.3) # max: Ruler.mm2pts(10) # padding: 30 # right_offset.length = right_offset.length # + sWControl.bounds.width # sIControl = @generateControlUI "strokeInterval", # position: meter.bounds.rightCenter.clone().add(right_offset) # min: Ruler.mm2pts(0.3) # max: Ruler.mm2pts(10) # padding: 30 resistance_ui = new paper.Group name: "resistance_ui" children: [meter] data: printable: false @addComponent resistance_ui # GEOMETRY GENERATION FUNCTIONS makeJouleHeater: (update=false)-> source = @getComponent "source" sink = @getComponent "sink" joule = @getComponent "joule" boundary = @getComponent "boundary" render_heater = source and sink if render_heater or update if joule then @deleteComponent "joule" params = boundaries: [boundary] source: source.position sink: sink.position joule = @serpentine params @joule_interaction() boundary.sendToBack() @circuit_status() make_terminals: ()-> boundary = @getComponent "boundary" params = boundaries: [boundary] source: boundary.getNearestPoint(boundary.bounds.topCenter) sink: boundary.getNearestPoint(boundary.bounds.bottomCenter) source_normal = boundary.getNormalAt(boundary.getOffsetOf(params.source)) sink_normal = boundary.getNormalAt(boundary.getOffsetOf(params.sink)) source_normal.length = -15 sink_normal.length = -15 source = new Magnet name: "source" magnets: ["C"] accepts: ["magnet_start_terminal", "magnet_end_terminal"] path: new paper.Path.Rectangle size: [60, 30] radius: 5 magnetClass: "magnet_sink" position: params.source.clone().add(source_normal) style: @styles.source_active() # source_handle = new paper.Path.Circle # radius: sink = new Magnet name: "sink" magnets: ["C"] accepts: ["magnet_start_terminal", "magnet_end_terminal"] path: new paper.Path.Circle magnetClass: "magnet_sink" radius: 15 position: params.sink.clone().add(sink_normal) style: @styles.sink_active(this) sink_path = sink.getComponent "magnet_component" tensioner = new paper.Path.Circle name: "PI:NAME:<NAME>END_PIensioner" position: sink_path.getPointAt(0) radius: 10 @setStyle tensioner, "active" @addComponents [source.ui, sink.ui, tensioner] tensioner.bringToFront() @tensioner_interaction() @terminal_interaction() serpentine: (options)-> options.strokeWidth = this.strokeWidth options.strokeInterval = this.strokeInterval options.heatColor = this.getRelationalColor() scope = this boundary = options.boundaries[0] axis_length = Math.abs(options.source.subtract(options.sink).length) if axis_length < 30 @setStyle boundary, "passive" return else heat_layer.activate() joule = HeatSketch.snake options if joule @setStyle boundary, "active" @deleteComponent "joule" @addComponent joule joule.sendToBack() else @deleteComponent "joule" return joule generateControlUI: (field, config)-> scope = this ui_layer.activate() group = new paper.Group name: "control_"+field text = new PointText name: field parent: group fillColor: 'black' fontFamily: 'Avenir' fontSize: 15 content: Ruler.pts2mm(this[field]).toFixed(1) + " mm" data: value: this[field] # console.log text.bounds.topCenter.add(0, -config.padding) increase = new paper.Path.Circle parent: group name: "increase_"+field radius: 15 fillColor: "black" position: text.bounds.topCenter.add(0, -config.padding) onMouseDown: ()-> val = text.data.value val = val + 0.3 if val > config.max val = config.max text.data.value = val text.content = Ruler.pts2mm(val).toFixed(1) + " mm" scope[field] = val scope.update() decrease = new paper.Path.Circle parent: group name: "decrease_"+field radius: 15 fillColor: "red" position: text.bounds.bottomCenter.add(0, config.padding) onMouseDown: ()-> val = text.data.value val = val - 0.3 if val <= config.min val = config.min text.data.value = val text.content = Ruler.pts2mm(val).toFixed(1) + " mm" scope[field] = val scope.update() group.position = config.position return group # CIRCUIT ANALYSIS last_resistance_str: "- Ω" last_resistance: 0 getResistance: (string = true)-> joule = @getComponent "joule" if not joule rtn = if string then this.last_resistance_str else this.last_resistance return rtn length = Ruler.pts2mm(joule.length) cross_sectional = MaterialLib.AgIC.thickness * Ruler.pts2mm(joule.strokeWidth) resistance = MaterialLib.AgIC.resistivity * (length / cross_sectional) this.last_resistance_str = resistance.toFixed(0) + "Ω" this.last_resistance = resistance rtn = if string then this.last_resistance_str else this.last_resistance return rtn getRelationalResistance: ()-> p = @getResistance(false)/500 if p > 1 return 1 else if p < 0 return 0 else return p getRelationalColor: ()-> c = HeatSim.temperatureColor(@getRelationalResistance(),with_white=false, reverse=true) return c
[ { "context": "r to the workspace of a {@link Project}\n\n @author Fabian M. <mail.fabianm@gmail.com>\n###\nclass Workspace\n\n\t#", "end": 145, "score": 0.9998472332954407, "start": 137, "tag": "NAME", "value": "Fabian M" }, { "context": "kspace of a {@link Project}\n\n @author Fabian M. <mail.fabianm@gmail.com>\n###\nclass Workspace\n\n\t###\n\t Constructs a new {@", "end": 170, "score": 0.9999338984489441, "start": 148, "tag": "EMAIL", "value": "mail.fabianm@gmail.com" } ]
kaffee/src/main/kaffee/project/workspace.coffee
fabianm/kaffee
1
Fs = require "fs" Path = require "path" ### The {@link Workspace} class is a pointer to the workspace of a {@link Project} @author Fabian M. <mail.fabianm@gmail.com> ### class Workspace ### Constructs a new {@link Workspace} instance. @since 0.1.1 @param path The path pointing to the workspace. ### constructor: (path = ".") -> @path = Path.resolve path ### Returns the path pointing to the workspace. @since 0.1.1 @return The path pointing to the workspace. ### getPath: -> @path ### Determines if this workspace exists or not. @since 0.1.1 @return <code>true</code> if this workspace exists, <code>false</code> otherwise. ### exists: -> Fs.existsSync @path ### Creates this workspace. @since 0.1.1 ### create: -> Fs.mkdirSync @path module.exports = Workspace
175187
Fs = require "fs" Path = require "path" ### The {@link Workspace} class is a pointer to the workspace of a {@link Project} @author <NAME>. <<EMAIL>> ### class Workspace ### Constructs a new {@link Workspace} instance. @since 0.1.1 @param path The path pointing to the workspace. ### constructor: (path = ".") -> @path = Path.resolve path ### Returns the path pointing to the workspace. @since 0.1.1 @return The path pointing to the workspace. ### getPath: -> @path ### Determines if this workspace exists or not. @since 0.1.1 @return <code>true</code> if this workspace exists, <code>false</code> otherwise. ### exists: -> Fs.existsSync @path ### Creates this workspace. @since 0.1.1 ### create: -> Fs.mkdirSync @path module.exports = Workspace
true
Fs = require "fs" Path = require "path" ### The {@link Workspace} class is a pointer to the workspace of a {@link Project} @author PI:NAME:<NAME>END_PI. <PI:EMAIL:<EMAIL>END_PI> ### class Workspace ### Constructs a new {@link Workspace} instance. @since 0.1.1 @param path The path pointing to the workspace. ### constructor: (path = ".") -> @path = Path.resolve path ### Returns the path pointing to the workspace. @since 0.1.1 @return The path pointing to the workspace. ### getPath: -> @path ### Determines if this workspace exists or not. @since 0.1.1 @return <code>true</code> if this workspace exists, <code>false</code> otherwise. ### exists: -> Fs.existsSync @path ### Creates this workspace. @since 0.1.1 ### create: -> Fs.mkdirSync @path module.exports = Workspace
[ { "context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s", "end": 61, "score": 0.9998447299003601, "start": 48, "tag": "NAME", "value": "Stephan Jorek" }, { "context": ",10], price:25.85, quantity: 15 }\n { name: 'Ties' , sizes: [2], price:3.99, quantity: 3 }\n ]\n ", "end": 2108, "score": 0.9962137937545776, "start": 2104, "tag": "NAME", "value": "Ties" }, { "context": "ie: { discount: 30, items:1 }\n favoriteChild: 'pat'\n children:\n pat:\n name: 'pat'\n ", "end": 2314, "score": 0.953662633895874, "start": 2311, "tag": "NAME", "value": "pat" }, { "context": "ld: 'pat'\n children:\n pat:\n name: 'pat'\n age: 28\n children:\n jay:", "end": 2359, "score": 0.998931884765625, "start": 2356, "tag": "NAME", "value": "pat" }, { "context": " 'pat'\n age: 28\n children:\n jay: { name: 'jay', age: 4 }\n bob: { name:", "end": 2406, "score": 0.8608047962188721, "start": 2405, "tag": "NAME", "value": "j" }, { "context": "age: 28\n children:\n jay: { name: 'jay', age: 4 }\n bob: { name: 'bob', age:8 }\n", "end": 2422, "score": 0.9991248250007629, "start": 2419, "tag": "NAME", "value": "jay" }, { "context": ": { name: 'jay', age: 4 }\n bob: { name: 'bob', age:8 }\n skip:\n name: 'skip'\n ", "end": 2461, "score": 0.9986304044723511, "start": 2458, "tag": "NAME", "value": "bob" }, { "context": "{ name: 'bob', age:8 }\n skip:\n name: 'skip'\n age: 30\n children:\n joe:", "end": 2503, "score": 0.9993622899055481, "start": 2499, "tag": "NAME", "value": "skip" }, { "context": "'skip'\n age: 30\n children:\n joe: { name: 'joe', age: 7 }\n dynamic: 0\n incre", "end": 2552, "score": 0.615990936756134, "start": 2549, "tag": "NAME", "value": "joe" }, { "context": "age: 30\n children:\n joe: { name: 'joe', age: 7 }\n dynamic: 0\n increment: (count) ", "end": 2566, "score": 0.9992515444755554, "start": 2563, "tag": "NAME", "value": "joe" }, { "context": ".*{sizes == 'M' || sizes == 9}\", [\n { name: 'Shirt', sizes: ['S','M','L'], price:14.50, quantity:", "end": 7396, "score": 0.8374711275100708, "start": 7394, "tag": "NAME", "value": "Sh" }, { "context": "','L'], price:14.50, quantity: 8 }\n { name: 'Shoes', sizes: [8,9,10], price:25.85, quantity: 15 ", "end": 7468, "score": 0.8007721304893494, "start": 7466, "tag": "NAME", "value": "Sh" }, { "context": " same name', ->\n egal \"\"\"\n favoriteChild = 'Kris';\n favoriteChild + $$favoriteChild;\n \"\"\", \"", "end": 10891, "score": 0.9997077584266663, "start": 10887, "tag": "NAME", "value": "Kris" }, { "context": "';\n favoriteChild + $$favoriteChild;\n \"\"\", \"Krispat\"\n", "end": 10948, "score": 0.9997794032096863, "start": 10941, "tag": "NAME", "value": "Krispat" } ]
spec/GoateeScriptTestSpec.coffee
sjorek/goatee-script.js
0
### ^ BSD 3-Clause License Copyright (c) 2017, Stephan Jorek All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### Benchmark = require 'benchmark' { evaluate, parse, render } = require '../src/GoateeScript' { isArray } = require '../src/Utility' #_ ?= null #expect ?= null #describe ?= null #xdescribe ?= null #it ?= null #xit ?= null #JSON ?= null describe "GoateeScript", -> data = clothes: [ { name: 'Shirt', sizes: ['S','M','L'], price:14.50, quantity: 8 } { name: 'Pants', sizes: [29,30,31,32], price:20.19, quantity: 6 } { name: 'Shoes', sizes: [8,9,10], price:25.85, quantity: 15 } { name: 'Ties' , sizes: [2], price:3.99, quantity: 3 } ] codes: alpha: { discount: 10, items:4 } beta: { discount: 20, items:2 } charlie: { discount: 30, items:1 } favoriteChild: 'pat' children: pat: name: 'pat' age: 28 children: jay: { name: 'jay', age: 4 } bob: { name: 'bob', age:8 } skip: name: 'skip' age: 30 children: joe: { name: 'joe', age: 7 } dynamic: 0 increment: (count) -> this.dynamic += count min: (a, b) -> return a unless b? return b unless a? if a.valueOf() <= b.valueOf() then a else b max: (a, b) -> return a unless b? return b unless a? if a.valueOf() >= b.valueOf() then a else b sum: sum = (a) -> return 0 unless a? if isArray a total = 0 for item in a total += sum item return total number = Number a if isNaN number then 0 else number benchmark = new Benchmark.Suite egal = (code, expected) -> expression = parse code expect(expression.evaluate(data)).toBe expected compare = (code, expected) -> expression = parse code expect(JSON.stringify(expression.evaluate(data))) .toBe JSON.stringify(expected) it 'can add two positive numbers', -> egal '1+1', 2 xit 'can add two positive numbers in given time', (done) -> benchmark .add('goatee-script : 1+1', -> evaluate('1+1')) .add('javascript : 1+1', -> 1+1) .add('javascript eval: 1+1', -> eval('1+1')) .on('cycle', (event) -> console.log(String(event.target)) ) .on('complete', () -> expect(@filter('fastest').pluck('name')[0]).toBe 'javascript : 1+1' done() ) .run({async: false }) it 'resolves expression vectors', -> expect(parse('5').vector).toBe false expect(parse('5+2').vector).toBe false #expect(parse('*').vector).toBe true #expect(parse('*.alpha').vector).toBe true #expect(parse('alpha.* * 12').vector).toBe true #expect(parse('alpha.*').vector).toBe true expect(parse('func(alpha)').vector).toBe false #expect(parse('func(*)').vector).toBe false #expect(parse('func(alpha.*.beta)').vector).toBe false it 'resolves one or multiple collapsing “undefined” values', -> statements = ['', ';;;;', ';/* nix */;'] for s in statements expect(evaluate(s)).toBe undefined expect(render(s)).toBe '' it 'resolves one or multiple “null” values', -> statements = ['null', 'null;null', 'null;null;null'] for s in statements expect(evaluate(s)).toBe null expect(render(s)).toBe s it 'resolves multiple “null” and collapsing “undefined” values', -> statements = [';null;null;;', 'null;;null;;', 'null;/*;null;*/null;;'] for s in statements expect(evaluate(s)).toBe null expect(render(s)).toBe 'null;null' it 'resolves scalar values (primitives)', -> egal "5", 5 egal "'5'", '5' egal "1 + 2", 3 egal "1 + 2 * 3", 7 egal "'a' + 'b'", 'ab' it 'resolves object access', -> egal "codes", data.codes egal "codes.alpha", data.codes.alpha egal "codes.alpha.discount", data.codes.alpha.discount egal "codes.discount", undefined xit 'resolves object with children access', -> compare "*", _.values data compare "codes.*", [data.codes.alpha, data.codes.beta, data.codes.charlie] compare "codes.*.discount", [10,20,30] compare "codes.*{discount > 10}", [data.codes.beta, data.codes.charlie] it 'resolves array access', -> # test numbers and indexers egal "clothes[0]", data.clothes[0] # test negative numbers and indexers egal "clothes[-1]", data.clothes[data.clothes.length-1] it 'resolves scope access', -> egal "children", data.children # because the children object contains no children property egal "children.children", undefined xit 'resolves children access', -> compare "children.*", [ data.children.pat data.children.skip ] compare "children.*.children", [ data.children.pat.children data.children.skip.children ] compare "children.*.children.*", [ data.children.pat.children.jay data.children.pat.children.bob data.children.skip.children.joe ] xit 'resolves object access predicates', -> # bare predicates no longer supported so use this[predicate] egal "@{clothes != null}", data compare "@{clothes == null}", undefined # predicates compare "children.*{name == 'skip'}", [data.children.skip] compare "children.*{children.*{age < 5}}", [data.children.pat] it 'resolves constructor access', -> egal "codes.constructor", undefined egal "codes.__proto__", undefined egal "codes.prototype", undefined it 'resolves prototype access', -> egal "codes + ''", data.codes.toString() egal "codes.toString()", data.codes.toString() egal "codes.valueOf()", data.codes.valueOf() egal "clothes.length", 4 xit 'resolves array access predicates', -> # get the sizes of clothes that are even. compare "clothes.*.sizes.*{@ % 2 == 0}", [30,32,8,10,2] compare "clothes.*{sizes == 'M' || sizes == 9}", [ { name: 'Shirt', sizes: ['S','M','L'], price:14.50, quantity: 8 } { name: 'Shoes', sizes: [8,9,10], price:25.85, quantity: 15 } ] it 'resolves context references', -> # test root references egal "@", data egal "$$", data compare "test = 1 ; $_", {test:1} # or more concisely egal "children[favoriteChild]", data.children.pat xit 'resolves context references with predicate', -> egal "children.*{name == favoriteChild}[0]", data.children.pat xit 'resolves context specific operation using .(local paths) syntax.', -> # context specific operation using .(local paths) syntax. egal "sum(clothes.*.(price * quantity))", 636.86 it 'resolves context reference function calls', -> # test min and max egal "min(12, 20)", 12 egal "max(30, 50)", 50 it 'resolves object and array literals', -> obj = {alpha:data.codes.alpha.discount, beta:2} ary = [3,2,data.codes.beta.discount] # test object literal compare '{alpha:codes.alpha.discount,"beta":2}', obj # test array literal compare '[3,2,codes.beta.discount]', ary # test object literal and array literal obj.charlie = ary compare '{alpha:codes.alpha.discount,' + \ '"beta":2,' + \ 'charlie:[3,2,codes.beta.discount]}', obj it 'resolves “if”/“else” conditions', -> # compares multiline expressions too data.dynamic = 0 egal """ if (codes != null) { increment(10); } else { increment(20); }; dynamic; """, 10 expect(data.dynamic).toBe 10 it 'resolves chained “if”/“else if”/“else” conditions', -> # compares multiline expressions too code = """ if (0 === dynamic) { increment(10); } else if (1 === dynamic) { increment(19); } else { increment(30 - dynamic); }; dynamic; """ data.dynamic = 0 egal code, 10 expect(data.dynamic).toBe 10 data.dynamic = 1 egal code, 20 expect(data.dynamic).toBe 20 data.dynamic = 2 egal code, 30 expect(data.dynamic).toBe 30 xit 'resolves “for”-loop and multiline statements', -> # compare for loop compare """ for (clothes) { p = price; q = quantity; p * q; } """, [ 116, 121.14000000000001, 387.75, 11.97 ] it 'resolves early terminating conditionals', -> # compare early termination of OR data.dynamic = 0 egal "increment(10) || increment(20); dynamic;", 10 expect(data.dynamic).toBe 10 # compare early termination of AND data.dynamic = 0 egal "increment(0) && increment(20); dynamic;", 0 expect(data.dynamic).toBe 0 # compare early termination of conditional data.dynamic = 0 egal "false ? increment(10) : increment(20); dynamic;", 20 expect(data.dynamic).toBe 20 it 'resolves all mathematical assignments', -> egal """ variable = 40 + 5; /* = 45 */ variable *= 10; /* = 450 */ variable /= 5; /* = 90 */ variable -= 40; /* = 50 */ variable += 15; /* = 65 */ variable++ ; /* = 66 */ variable-- ; /* = 65 */ ++variable ; /* = 66 */ --variable ; /* = 65 */ """, 65 it 'resolves context assignments', -> egal """ variable = codes; variable.alpha; """, data.codes.alpha it 'resolves local variable and context property having the same name', -> egal """ favoriteChild = 'Kris'; favoriteChild + $$favoriteChild; """, "Krispat"
103022
### ^ BSD 3-Clause License Copyright (c) 2017, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### Benchmark = require 'benchmark' { evaluate, parse, render } = require '../src/GoateeScript' { isArray } = require '../src/Utility' #_ ?= null #expect ?= null #describe ?= null #xdescribe ?= null #it ?= null #xit ?= null #JSON ?= null describe "GoateeScript", -> data = clothes: [ { name: 'Shirt', sizes: ['S','M','L'], price:14.50, quantity: 8 } { name: 'Pants', sizes: [29,30,31,32], price:20.19, quantity: 6 } { name: 'Shoes', sizes: [8,9,10], price:25.85, quantity: 15 } { name: '<NAME>' , sizes: [2], price:3.99, quantity: 3 } ] codes: alpha: { discount: 10, items:4 } beta: { discount: 20, items:2 } charlie: { discount: 30, items:1 } favoriteChild: '<NAME>' children: pat: name: '<NAME>' age: 28 children: <NAME>ay: { name: '<NAME>', age: 4 } bob: { name: '<NAME>', age:8 } skip: name: '<NAME>' age: 30 children: <NAME>: { name: '<NAME>', age: 7 } dynamic: 0 increment: (count) -> this.dynamic += count min: (a, b) -> return a unless b? return b unless a? if a.valueOf() <= b.valueOf() then a else b max: (a, b) -> return a unless b? return b unless a? if a.valueOf() >= b.valueOf() then a else b sum: sum = (a) -> return 0 unless a? if isArray a total = 0 for item in a total += sum item return total number = Number a if isNaN number then 0 else number benchmark = new Benchmark.Suite egal = (code, expected) -> expression = parse code expect(expression.evaluate(data)).toBe expected compare = (code, expected) -> expression = parse code expect(JSON.stringify(expression.evaluate(data))) .toBe JSON.stringify(expected) it 'can add two positive numbers', -> egal '1+1', 2 xit 'can add two positive numbers in given time', (done) -> benchmark .add('goatee-script : 1+1', -> evaluate('1+1')) .add('javascript : 1+1', -> 1+1) .add('javascript eval: 1+1', -> eval('1+1')) .on('cycle', (event) -> console.log(String(event.target)) ) .on('complete', () -> expect(@filter('fastest').pluck('name')[0]).toBe 'javascript : 1+1' done() ) .run({async: false }) it 'resolves expression vectors', -> expect(parse('5').vector).toBe false expect(parse('5+2').vector).toBe false #expect(parse('*').vector).toBe true #expect(parse('*.alpha').vector).toBe true #expect(parse('alpha.* * 12').vector).toBe true #expect(parse('alpha.*').vector).toBe true expect(parse('func(alpha)').vector).toBe false #expect(parse('func(*)').vector).toBe false #expect(parse('func(alpha.*.beta)').vector).toBe false it 'resolves one or multiple collapsing “undefined” values', -> statements = ['', ';;;;', ';/* nix */;'] for s in statements expect(evaluate(s)).toBe undefined expect(render(s)).toBe '' it 'resolves one or multiple “null” values', -> statements = ['null', 'null;null', 'null;null;null'] for s in statements expect(evaluate(s)).toBe null expect(render(s)).toBe s it 'resolves multiple “null” and collapsing “undefined” values', -> statements = [';null;null;;', 'null;;null;;', 'null;/*;null;*/null;;'] for s in statements expect(evaluate(s)).toBe null expect(render(s)).toBe 'null;null' it 'resolves scalar values (primitives)', -> egal "5", 5 egal "'5'", '5' egal "1 + 2", 3 egal "1 + 2 * 3", 7 egal "'a' + 'b'", 'ab' it 'resolves object access', -> egal "codes", data.codes egal "codes.alpha", data.codes.alpha egal "codes.alpha.discount", data.codes.alpha.discount egal "codes.discount", undefined xit 'resolves object with children access', -> compare "*", _.values data compare "codes.*", [data.codes.alpha, data.codes.beta, data.codes.charlie] compare "codes.*.discount", [10,20,30] compare "codes.*{discount > 10}", [data.codes.beta, data.codes.charlie] it 'resolves array access', -> # test numbers and indexers egal "clothes[0]", data.clothes[0] # test negative numbers and indexers egal "clothes[-1]", data.clothes[data.clothes.length-1] it 'resolves scope access', -> egal "children", data.children # because the children object contains no children property egal "children.children", undefined xit 'resolves children access', -> compare "children.*", [ data.children.pat data.children.skip ] compare "children.*.children", [ data.children.pat.children data.children.skip.children ] compare "children.*.children.*", [ data.children.pat.children.jay data.children.pat.children.bob data.children.skip.children.joe ] xit 'resolves object access predicates', -> # bare predicates no longer supported so use this[predicate] egal "@{clothes != null}", data compare "@{clothes == null}", undefined # predicates compare "children.*{name == 'skip'}", [data.children.skip] compare "children.*{children.*{age < 5}}", [data.children.pat] it 'resolves constructor access', -> egal "codes.constructor", undefined egal "codes.__proto__", undefined egal "codes.prototype", undefined it 'resolves prototype access', -> egal "codes + ''", data.codes.toString() egal "codes.toString()", data.codes.toString() egal "codes.valueOf()", data.codes.valueOf() egal "clothes.length", 4 xit 'resolves array access predicates', -> # get the sizes of clothes that are even. compare "clothes.*.sizes.*{@ % 2 == 0}", [30,32,8,10,2] compare "clothes.*{sizes == 'M' || sizes == 9}", [ { name: '<NAME>irt', sizes: ['S','M','L'], price:14.50, quantity: 8 } { name: '<NAME>oes', sizes: [8,9,10], price:25.85, quantity: 15 } ] it 'resolves context references', -> # test root references egal "@", data egal "$$", data compare "test = 1 ; $_", {test:1} # or more concisely egal "children[favoriteChild]", data.children.pat xit 'resolves context references with predicate', -> egal "children.*{name == favoriteChild}[0]", data.children.pat xit 'resolves context specific operation using .(local paths) syntax.', -> # context specific operation using .(local paths) syntax. egal "sum(clothes.*.(price * quantity))", 636.86 it 'resolves context reference function calls', -> # test min and max egal "min(12, 20)", 12 egal "max(30, 50)", 50 it 'resolves object and array literals', -> obj = {alpha:data.codes.alpha.discount, beta:2} ary = [3,2,data.codes.beta.discount] # test object literal compare '{alpha:codes.alpha.discount,"beta":2}', obj # test array literal compare '[3,2,codes.beta.discount]', ary # test object literal and array literal obj.charlie = ary compare '{alpha:codes.alpha.discount,' + \ '"beta":2,' + \ 'charlie:[3,2,codes.beta.discount]}', obj it 'resolves “if”/“else” conditions', -> # compares multiline expressions too data.dynamic = 0 egal """ if (codes != null) { increment(10); } else { increment(20); }; dynamic; """, 10 expect(data.dynamic).toBe 10 it 'resolves chained “if”/“else if”/“else” conditions', -> # compares multiline expressions too code = """ if (0 === dynamic) { increment(10); } else if (1 === dynamic) { increment(19); } else { increment(30 - dynamic); }; dynamic; """ data.dynamic = 0 egal code, 10 expect(data.dynamic).toBe 10 data.dynamic = 1 egal code, 20 expect(data.dynamic).toBe 20 data.dynamic = 2 egal code, 30 expect(data.dynamic).toBe 30 xit 'resolves “for”-loop and multiline statements', -> # compare for loop compare """ for (clothes) { p = price; q = quantity; p * q; } """, [ 116, 121.14000000000001, 387.75, 11.97 ] it 'resolves early terminating conditionals', -> # compare early termination of OR data.dynamic = 0 egal "increment(10) || increment(20); dynamic;", 10 expect(data.dynamic).toBe 10 # compare early termination of AND data.dynamic = 0 egal "increment(0) && increment(20); dynamic;", 0 expect(data.dynamic).toBe 0 # compare early termination of conditional data.dynamic = 0 egal "false ? increment(10) : increment(20); dynamic;", 20 expect(data.dynamic).toBe 20 it 'resolves all mathematical assignments', -> egal """ variable = 40 + 5; /* = 45 */ variable *= 10; /* = 450 */ variable /= 5; /* = 90 */ variable -= 40; /* = 50 */ variable += 15; /* = 65 */ variable++ ; /* = 66 */ variable-- ; /* = 65 */ ++variable ; /* = 66 */ --variable ; /* = 65 */ """, 65 it 'resolves context assignments', -> egal """ variable = codes; variable.alpha; """, data.codes.alpha it 'resolves local variable and context property having the same name', -> egal """ favoriteChild = '<NAME>'; favoriteChild + $$favoriteChild; """, "<NAME>"
true
### ^ BSD 3-Clause License Copyright (c) 2017, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### Benchmark = require 'benchmark' { evaluate, parse, render } = require '../src/GoateeScript' { isArray } = require '../src/Utility' #_ ?= null #expect ?= null #describe ?= null #xdescribe ?= null #it ?= null #xit ?= null #JSON ?= null describe "GoateeScript", -> data = clothes: [ { name: 'Shirt', sizes: ['S','M','L'], price:14.50, quantity: 8 } { name: 'Pants', sizes: [29,30,31,32], price:20.19, quantity: 6 } { name: 'Shoes', sizes: [8,9,10], price:25.85, quantity: 15 } { name: 'PI:NAME:<NAME>END_PI' , sizes: [2], price:3.99, quantity: 3 } ] codes: alpha: { discount: 10, items:4 } beta: { discount: 20, items:2 } charlie: { discount: 30, items:1 } favoriteChild: 'PI:NAME:<NAME>END_PI' children: pat: name: 'PI:NAME:<NAME>END_PI' age: 28 children: PI:NAME:<NAME>END_PIay: { name: 'PI:NAME:<NAME>END_PI', age: 4 } bob: { name: 'PI:NAME:<NAME>END_PI', age:8 } skip: name: 'PI:NAME:<NAME>END_PI' age: 30 children: PI:NAME:<NAME>END_PI: { name: 'PI:NAME:<NAME>END_PI', age: 7 } dynamic: 0 increment: (count) -> this.dynamic += count min: (a, b) -> return a unless b? return b unless a? if a.valueOf() <= b.valueOf() then a else b max: (a, b) -> return a unless b? return b unless a? if a.valueOf() >= b.valueOf() then a else b sum: sum = (a) -> return 0 unless a? if isArray a total = 0 for item in a total += sum item return total number = Number a if isNaN number then 0 else number benchmark = new Benchmark.Suite egal = (code, expected) -> expression = parse code expect(expression.evaluate(data)).toBe expected compare = (code, expected) -> expression = parse code expect(JSON.stringify(expression.evaluate(data))) .toBe JSON.stringify(expected) it 'can add two positive numbers', -> egal '1+1', 2 xit 'can add two positive numbers in given time', (done) -> benchmark .add('goatee-script : 1+1', -> evaluate('1+1')) .add('javascript : 1+1', -> 1+1) .add('javascript eval: 1+1', -> eval('1+1')) .on('cycle', (event) -> console.log(String(event.target)) ) .on('complete', () -> expect(@filter('fastest').pluck('name')[0]).toBe 'javascript : 1+1' done() ) .run({async: false }) it 'resolves expression vectors', -> expect(parse('5').vector).toBe false expect(parse('5+2').vector).toBe false #expect(parse('*').vector).toBe true #expect(parse('*.alpha').vector).toBe true #expect(parse('alpha.* * 12').vector).toBe true #expect(parse('alpha.*').vector).toBe true expect(parse('func(alpha)').vector).toBe false #expect(parse('func(*)').vector).toBe false #expect(parse('func(alpha.*.beta)').vector).toBe false it 'resolves one or multiple collapsing “undefined” values', -> statements = ['', ';;;;', ';/* nix */;'] for s in statements expect(evaluate(s)).toBe undefined expect(render(s)).toBe '' it 'resolves one or multiple “null” values', -> statements = ['null', 'null;null', 'null;null;null'] for s in statements expect(evaluate(s)).toBe null expect(render(s)).toBe s it 'resolves multiple “null” and collapsing “undefined” values', -> statements = [';null;null;;', 'null;;null;;', 'null;/*;null;*/null;;'] for s in statements expect(evaluate(s)).toBe null expect(render(s)).toBe 'null;null' it 'resolves scalar values (primitives)', -> egal "5", 5 egal "'5'", '5' egal "1 + 2", 3 egal "1 + 2 * 3", 7 egal "'a' + 'b'", 'ab' it 'resolves object access', -> egal "codes", data.codes egal "codes.alpha", data.codes.alpha egal "codes.alpha.discount", data.codes.alpha.discount egal "codes.discount", undefined xit 'resolves object with children access', -> compare "*", _.values data compare "codes.*", [data.codes.alpha, data.codes.beta, data.codes.charlie] compare "codes.*.discount", [10,20,30] compare "codes.*{discount > 10}", [data.codes.beta, data.codes.charlie] it 'resolves array access', -> # test numbers and indexers egal "clothes[0]", data.clothes[0] # test negative numbers and indexers egal "clothes[-1]", data.clothes[data.clothes.length-1] it 'resolves scope access', -> egal "children", data.children # because the children object contains no children property egal "children.children", undefined xit 'resolves children access', -> compare "children.*", [ data.children.pat data.children.skip ] compare "children.*.children", [ data.children.pat.children data.children.skip.children ] compare "children.*.children.*", [ data.children.pat.children.jay data.children.pat.children.bob data.children.skip.children.joe ] xit 'resolves object access predicates', -> # bare predicates no longer supported so use this[predicate] egal "@{clothes != null}", data compare "@{clothes == null}", undefined # predicates compare "children.*{name == 'skip'}", [data.children.skip] compare "children.*{children.*{age < 5}}", [data.children.pat] it 'resolves constructor access', -> egal "codes.constructor", undefined egal "codes.__proto__", undefined egal "codes.prototype", undefined it 'resolves prototype access', -> egal "codes + ''", data.codes.toString() egal "codes.toString()", data.codes.toString() egal "codes.valueOf()", data.codes.valueOf() egal "clothes.length", 4 xit 'resolves array access predicates', -> # get the sizes of clothes that are even. compare "clothes.*.sizes.*{@ % 2 == 0}", [30,32,8,10,2] compare "clothes.*{sizes == 'M' || sizes == 9}", [ { name: 'PI:NAME:<NAME>END_PIirt', sizes: ['S','M','L'], price:14.50, quantity: 8 } { name: 'PI:NAME:<NAME>END_PIoes', sizes: [8,9,10], price:25.85, quantity: 15 } ] it 'resolves context references', -> # test root references egal "@", data egal "$$", data compare "test = 1 ; $_", {test:1} # or more concisely egal "children[favoriteChild]", data.children.pat xit 'resolves context references with predicate', -> egal "children.*{name == favoriteChild}[0]", data.children.pat xit 'resolves context specific operation using .(local paths) syntax.', -> # context specific operation using .(local paths) syntax. egal "sum(clothes.*.(price * quantity))", 636.86 it 'resolves context reference function calls', -> # test min and max egal "min(12, 20)", 12 egal "max(30, 50)", 50 it 'resolves object and array literals', -> obj = {alpha:data.codes.alpha.discount, beta:2} ary = [3,2,data.codes.beta.discount] # test object literal compare '{alpha:codes.alpha.discount,"beta":2}', obj # test array literal compare '[3,2,codes.beta.discount]', ary # test object literal and array literal obj.charlie = ary compare '{alpha:codes.alpha.discount,' + \ '"beta":2,' + \ 'charlie:[3,2,codes.beta.discount]}', obj it 'resolves “if”/“else” conditions', -> # compares multiline expressions too data.dynamic = 0 egal """ if (codes != null) { increment(10); } else { increment(20); }; dynamic; """, 10 expect(data.dynamic).toBe 10 it 'resolves chained “if”/“else if”/“else” conditions', -> # compares multiline expressions too code = """ if (0 === dynamic) { increment(10); } else if (1 === dynamic) { increment(19); } else { increment(30 - dynamic); }; dynamic; """ data.dynamic = 0 egal code, 10 expect(data.dynamic).toBe 10 data.dynamic = 1 egal code, 20 expect(data.dynamic).toBe 20 data.dynamic = 2 egal code, 30 expect(data.dynamic).toBe 30 xit 'resolves “for”-loop and multiline statements', -> # compare for loop compare """ for (clothes) { p = price; q = quantity; p * q; } """, [ 116, 121.14000000000001, 387.75, 11.97 ] it 'resolves early terminating conditionals', -> # compare early termination of OR data.dynamic = 0 egal "increment(10) || increment(20); dynamic;", 10 expect(data.dynamic).toBe 10 # compare early termination of AND data.dynamic = 0 egal "increment(0) && increment(20); dynamic;", 0 expect(data.dynamic).toBe 0 # compare early termination of conditional data.dynamic = 0 egal "false ? increment(10) : increment(20); dynamic;", 20 expect(data.dynamic).toBe 20 it 'resolves all mathematical assignments', -> egal """ variable = 40 + 5; /* = 45 */ variable *= 10; /* = 450 */ variable /= 5; /* = 90 */ variable -= 40; /* = 50 */ variable += 15; /* = 65 */ variable++ ; /* = 66 */ variable-- ; /* = 65 */ ++variable ; /* = 66 */ --variable ; /* = 65 */ """, 65 it 'resolves context assignments', -> egal """ variable = codes; variable.alpha; """, data.codes.alpha it 'resolves local variable and context property having the same name', -> egal """ favoriteChild = 'PI:NAME:<NAME>END_PI'; favoriteChild + $$favoriteChild; """, "PI:NAME:<NAME>END_PI"
[ { "context": "#\n# grunt-md-templator\n# https://github.com/realyze/grunt-md-templator\n#\n# Copyright (c) 2013 Tomas B", "end": 51, "score": 0.9988315105438232, "start": 44, "tag": "USERNAME", "value": "realyze" }, { "context": "/realyze/grunt-md-templator\n#\n# Copyright (c) 2013 Tomas Brambora\n# Licensed under the MIT license.\n#\n\n'use strict'", "end": 108, "score": 0.9998246431350708, "start": 94, "tag": "NAME", "value": "Tomas Brambora" } ]
tasks/md_to_html.coffee
salsita/grunt-md-templator
0
# # grunt-md-templator # https://github.com/realyze/grunt-md-templator # # Copyright (c) 2013 Tomas Brambora # Licensed under the MIT license. # 'use strict' module.exports = (grunt) -> _ = require 'underscore' _s = require 'underscore.string' _.mixin(_s.exports()) {markdown} = require('markdown') beautifyHTML = require('js-beautify').html Entities = require('html-entities').AllHtmlEntities {decode} = new Entities() fspath = require 'path' mkdirp = require 'mkdirp' # Global options hash. _options = {} # Returns -1 if tag1 is less important than tag2, 0 if they're the same # and +1 if tag2 is more important. # The importance is based on the `options.tags` array. compareTags = (tag1, tag2) -> tagIndex = _.partial _.indexOf, _options.tags if tagIndex(tag1) > (tagIndex tag2) return -1 if tagIndex(tag1) == (tagIndex tag2) return 0 return 1 isBlockTag = (tag) -> tag.indexOf('block') == 0 getBlockName = (data) -> data[0][1].replace(/---\s*([^-\s]+)\s*---/, '$1') # Inserts a DOM region into the DOM region tree. insert = (data, root) -> tag = data[0][0] childTag = _.last _.pluck root.children, 'tag' # Handle blocks. Every block "inherits" heading level from # its parent header. Block ends when we either find a new block # tag or when the parent heading section ends. if isBlockTag(tag) if not root.tag? # It's the very first level of the tree, so just recurse in. return insert(data, _.last(root.children)) if childTag? and isBlockTag(childTag) # Current tag is a block and the last delimiter was a block => # end the previous block and start a new sibling block (with the # same heading level). tag = data[0][0] = childTag if _.isEmpty(root.children) # We've just found a new block without predecesors => start # a new block with parent heading level. tag = data[0][0] = "block-#{root.tag}" if _.isEmpty(root.children) or compareTags(tag, childTag) >= 0 # Note: The stringify/parse dance is necessary because renderJsonML is # changing data object. getHTML = (data) -> _.union(['html'], JSON.parse JSON.stringify data) metadata = getMetadata data root.children.push id: metadata.id metadata: metadata content: markdown.renderJsonML(getHTML data) header: markdown.renderJsonML(getHTML [data[0]]) body: markdown.renderJsonML(getHTML _.rest(data)) children: [] tag: tag isBlock: isBlockTag(tag) name: if isBlockTag(tag) then getBlockName(data) else null html: null # Filled later on. blocks: {} # Filled later on. if _options.decode # Make sure we decode the HTML entities. for attr in ['content', 'header', 'body'] _.last(root.children)[attr] = decode _.last(root.children)[attr] return root return insert(data, _.last(root.children)) processFile = (f) -> # Read'n'parse the md file. text = grunt.file.read f html = markdown.toHTMLTree markdown.parse text findDelimiter = (row) -> row[0] in _options.tags or (typeof(row[1]) is 'string' and row[1].match(/^---[^-]+---$/)) # Find all the relevant elements (i.e., headers) in JsonML. elemRows = _.filter html, _.isArray tagRows = _.filter elemRows, findDelimiter tagRows = _.map tagRows, (row) -> if typeof(row[1]) is 'string' and row[1].match(/^---[^-]+---$/) row[0] = 'block' return row blockTags = ("block-#{tag}" for tag in _options.tags) # ## Trick: # For every tag that creates scope, create it's block element child and # give one less priority level. # We use this to compare tag priorities (so that a block nested withing # an e.g. `h2` scope will have lower priority than `h2` but bigger than `h3`). _options.tags = _.flatten _.zip _options.tags, blockTags # ## Trick: # Add level-yet-to-be-determined block to the end of _options.tags (i.e., give # it the least priority). # That way it will always have a lower priority than any non-block tag we # find and hence will become it's child. _options.tags.push 'block' grunt.log.debug 'tagRows', tagRows grunt.log.debug '_options.tags', _options.tags # Parse the JsonML tree to get the "HTML regions" that correspond to each # header. Simply put, this splits the tree using 'h?' as separators). # # The idea here is that each header starts a new region and we want an # id for that region and the text before the next region starts. We'll # feed this info into the template and get a nice HTML partial. data = _.map tagRows, (tagRow, pos) -> index = _.indexOf html, tagRow next = tagRows[pos + 1] regionEnd = if next? then _.indexOf(html, next) else html.length return html.slice index, regionEnd root = {children: []} # Create the DOM region tree (we'll pass this tree to the # template later on). for d in data insert d, root root = findChildBlocks(root) root = findHTMLSubtrees(root) grunt.log.debug JSON.stringify root, null, 2 return root # DFS the tree and assign a `blocks` hash property to each node. The property # contains child nodes which are blocks. This is mainly for convenience so # that users can access the block by `node.blocks.<myBlockName>` shortcut. findChildBlocks = (root) -> root.blocks = {} for child in root.children findChildBlocks(child) if child.isBlock root.blocks[child.name] = child return root # DFS the tree and assign `html` property to each node. The property contains # the HTML content of the subtree (kind of like jQuery's `html()` method). findHTMLSubtrees = (root) -> for child in root.children findHTMLSubtrees(child) if root.children.length > 0 childHTML = _.pluck(root.children, 'html').join('') else childHTML = "" if root.isBlock # We're adding `body` for blocks because we don't want to include # the block element itself (which would happen if we included `content`). root.html = (root.body or '') + childHTML else root.html = (root.content or '') + childHTML root.html = _.trim(root.html) return root # Returns metadata for a region (accessible in the template). getMetadata = (data) -> grunt.log.debug 'data', data text = _.last data[0] {metadata_pattern} = _options match = text.match metadata_pattern metadata = {} if match # Strip the metadata pattern. data[0][data[0].length - 1] = _.trim text.replace(metadata_pattern, '') metadata = JSON.parse match[1] metadata.id or= _(data[0]).chain().last().slugify().value().toLowerCase() grunt.log.debug 'metadata', metadata return metadata grunt.registerMultiTask 'md_to_html', 'Turn markdown & template into HTML.', -> # Default options. _options = @options metadata_pattern: /{(.+)}/ tags: ['h1', 'h2', 'h3'] _.each @files, ({src, template, dest, ext}) => files = _.filter src, (filepath) -> if not grunt.file.exists filepath grunt.log.warn "Source file #{filepath} not found." return false return true # Parse the Markdown files specified in the currently processed # file dict. parsedFilesTuples = _.map files, (file) -> [file, processFile(file)] # Expand the specified template for each parsed file (with the data # compiled from the md file). _.each parsedFilesTuples, ([filepath, data]) -> tpl = template or _options.template if not _options.multiple_files grunt.file.copy tpl, dest, process: (contents, path) -> html = grunt.template.process contents, data: _.extend(data, _options.data) # Pretty print the html. return if _options.pretty then beautifyHTML(html) else html else splitIntoMultipleFiles(data, tpl, dest, ext) getDataLeaves = (data, pathToRoot=[], res) -> for child in data.children #parent = if data.id then [data.id] else [] getDataLeaves(child, _.union(pathToRoot, [data]), res) # Don't forget the leave node. pathToRoot.push(data) # We're only interested in the leaves. return unless _.isEmpty(data.children) # Forget the first part (that's the "header"). res.push _.rest(pathToRoot) # Creates multiple HTML files from `data`, each HTML file will be based on # template `tpl`, wil be stored in `dest` directory (plus the path determined # by the ids on the path to the section in the markdown document) and will # have `ext` extension. splitIntoMultipleFiles = (data, tpl, dest, ext) -> # Leaves is an array of arrays (paths from leaf to root in the markdown # document). leaves = [] getDataLeaves data, [], leaves # We have e.g. `clients/overview` and `clients/foo/bar` now but we want # `clients` and `clients/foo` too. leavesIncludingBlocks = _.union leaves, (_.initial(p) for p in leaves) # There's a lot of duplicates now, let's remove them to speed things up. leavesIncludingBlocks = _.uniq leavesIncludingBlocks, (leafPath) -> _.pluck(leafPath, 'id').join ' ' # Blocks are supposed to be invisible. So lets remove them (otherwise we would # get paths with ids like `-- front --` and `-- back --`). leaves = _.map leavesIncludingBlocks, (path) -> return _.reject path, (node) -> node.isBlock # We might have gotten some empty paths, let's get rid of those. nonEmptyLeaves = _.filter leaves, (path) -> path.length > 0 nodesPaths = _.map nonEmptyLeaves, (leafPath) -> # `parts` will be the path to the new HTML page produced from the # markdown section. parts = _.union([dest], _.pluck(leafPath, 'id')) leafDest = fspath.join.apply @, parts leafDest = "#{leafDest}#{ext}" return [leafPath, leafDest] for [nodes, path] in nodesPaths mkdirp.sync fspath.dirname(path) # Let's create the actual HTML file now. grunt.file.copy tpl, path, process: (contents, path) -> html = grunt.template.process contents, data: _.extend({ section: _.last(nodes) ids: _.pluck(nodes, 'id') all: data root: nodes[0] }, _options.data) # Pretty print the html. return if _options.pretty then beautifyHTML(html) else html
100671
# # grunt-md-templator # https://github.com/realyze/grunt-md-templator # # Copyright (c) 2013 <NAME> # Licensed under the MIT license. # 'use strict' module.exports = (grunt) -> _ = require 'underscore' _s = require 'underscore.string' _.mixin(_s.exports()) {markdown} = require('markdown') beautifyHTML = require('js-beautify').html Entities = require('html-entities').AllHtmlEntities {decode} = new Entities() fspath = require 'path' mkdirp = require 'mkdirp' # Global options hash. _options = {} # Returns -1 if tag1 is less important than tag2, 0 if they're the same # and +1 if tag2 is more important. # The importance is based on the `options.tags` array. compareTags = (tag1, tag2) -> tagIndex = _.partial _.indexOf, _options.tags if tagIndex(tag1) > (tagIndex tag2) return -1 if tagIndex(tag1) == (tagIndex tag2) return 0 return 1 isBlockTag = (tag) -> tag.indexOf('block') == 0 getBlockName = (data) -> data[0][1].replace(/---\s*([^-\s]+)\s*---/, '$1') # Inserts a DOM region into the DOM region tree. insert = (data, root) -> tag = data[0][0] childTag = _.last _.pluck root.children, 'tag' # Handle blocks. Every block "inherits" heading level from # its parent header. Block ends when we either find a new block # tag or when the parent heading section ends. if isBlockTag(tag) if not root.tag? # It's the very first level of the tree, so just recurse in. return insert(data, _.last(root.children)) if childTag? and isBlockTag(childTag) # Current tag is a block and the last delimiter was a block => # end the previous block and start a new sibling block (with the # same heading level). tag = data[0][0] = childTag if _.isEmpty(root.children) # We've just found a new block without predecesors => start # a new block with parent heading level. tag = data[0][0] = "block-#{root.tag}" if _.isEmpty(root.children) or compareTags(tag, childTag) >= 0 # Note: The stringify/parse dance is necessary because renderJsonML is # changing data object. getHTML = (data) -> _.union(['html'], JSON.parse JSON.stringify data) metadata = getMetadata data root.children.push id: metadata.id metadata: metadata content: markdown.renderJsonML(getHTML data) header: markdown.renderJsonML(getHTML [data[0]]) body: markdown.renderJsonML(getHTML _.rest(data)) children: [] tag: tag isBlock: isBlockTag(tag) name: if isBlockTag(tag) then getBlockName(data) else null html: null # Filled later on. blocks: {} # Filled later on. if _options.decode # Make sure we decode the HTML entities. for attr in ['content', 'header', 'body'] _.last(root.children)[attr] = decode _.last(root.children)[attr] return root return insert(data, _.last(root.children)) processFile = (f) -> # Read'n'parse the md file. text = grunt.file.read f html = markdown.toHTMLTree markdown.parse text findDelimiter = (row) -> row[0] in _options.tags or (typeof(row[1]) is 'string' and row[1].match(/^---[^-]+---$/)) # Find all the relevant elements (i.e., headers) in JsonML. elemRows = _.filter html, _.isArray tagRows = _.filter elemRows, findDelimiter tagRows = _.map tagRows, (row) -> if typeof(row[1]) is 'string' and row[1].match(/^---[^-]+---$/) row[0] = 'block' return row blockTags = ("block-#{tag}" for tag in _options.tags) # ## Trick: # For every tag that creates scope, create it's block element child and # give one less priority level. # We use this to compare tag priorities (so that a block nested withing # an e.g. `h2` scope will have lower priority than `h2` but bigger than `h3`). _options.tags = _.flatten _.zip _options.tags, blockTags # ## Trick: # Add level-yet-to-be-determined block to the end of _options.tags (i.e., give # it the least priority). # That way it will always have a lower priority than any non-block tag we # find and hence will become it's child. _options.tags.push 'block' grunt.log.debug 'tagRows', tagRows grunt.log.debug '_options.tags', _options.tags # Parse the JsonML tree to get the "HTML regions" that correspond to each # header. Simply put, this splits the tree using 'h?' as separators). # # The idea here is that each header starts a new region and we want an # id for that region and the text before the next region starts. We'll # feed this info into the template and get a nice HTML partial. data = _.map tagRows, (tagRow, pos) -> index = _.indexOf html, tagRow next = tagRows[pos + 1] regionEnd = if next? then _.indexOf(html, next) else html.length return html.slice index, regionEnd root = {children: []} # Create the DOM region tree (we'll pass this tree to the # template later on). for d in data insert d, root root = findChildBlocks(root) root = findHTMLSubtrees(root) grunt.log.debug JSON.stringify root, null, 2 return root # DFS the tree and assign a `blocks` hash property to each node. The property # contains child nodes which are blocks. This is mainly for convenience so # that users can access the block by `node.blocks.<myBlockName>` shortcut. findChildBlocks = (root) -> root.blocks = {} for child in root.children findChildBlocks(child) if child.isBlock root.blocks[child.name] = child return root # DFS the tree and assign `html` property to each node. The property contains # the HTML content of the subtree (kind of like jQuery's `html()` method). findHTMLSubtrees = (root) -> for child in root.children findHTMLSubtrees(child) if root.children.length > 0 childHTML = _.pluck(root.children, 'html').join('') else childHTML = "" if root.isBlock # We're adding `body` for blocks because we don't want to include # the block element itself (which would happen if we included `content`). root.html = (root.body or '') + childHTML else root.html = (root.content or '') + childHTML root.html = _.trim(root.html) return root # Returns metadata for a region (accessible in the template). getMetadata = (data) -> grunt.log.debug 'data', data text = _.last data[0] {metadata_pattern} = _options match = text.match metadata_pattern metadata = {} if match # Strip the metadata pattern. data[0][data[0].length - 1] = _.trim text.replace(metadata_pattern, '') metadata = JSON.parse match[1] metadata.id or= _(data[0]).chain().last().slugify().value().toLowerCase() grunt.log.debug 'metadata', metadata return metadata grunt.registerMultiTask 'md_to_html', 'Turn markdown & template into HTML.', -> # Default options. _options = @options metadata_pattern: /{(.+)}/ tags: ['h1', 'h2', 'h3'] _.each @files, ({src, template, dest, ext}) => files = _.filter src, (filepath) -> if not grunt.file.exists filepath grunt.log.warn "Source file #{filepath} not found." return false return true # Parse the Markdown files specified in the currently processed # file dict. parsedFilesTuples = _.map files, (file) -> [file, processFile(file)] # Expand the specified template for each parsed file (with the data # compiled from the md file). _.each parsedFilesTuples, ([filepath, data]) -> tpl = template or _options.template if not _options.multiple_files grunt.file.copy tpl, dest, process: (contents, path) -> html = grunt.template.process contents, data: _.extend(data, _options.data) # Pretty print the html. return if _options.pretty then beautifyHTML(html) else html else splitIntoMultipleFiles(data, tpl, dest, ext) getDataLeaves = (data, pathToRoot=[], res) -> for child in data.children #parent = if data.id then [data.id] else [] getDataLeaves(child, _.union(pathToRoot, [data]), res) # Don't forget the leave node. pathToRoot.push(data) # We're only interested in the leaves. return unless _.isEmpty(data.children) # Forget the first part (that's the "header"). res.push _.rest(pathToRoot) # Creates multiple HTML files from `data`, each HTML file will be based on # template `tpl`, wil be stored in `dest` directory (plus the path determined # by the ids on the path to the section in the markdown document) and will # have `ext` extension. splitIntoMultipleFiles = (data, tpl, dest, ext) -> # Leaves is an array of arrays (paths from leaf to root in the markdown # document). leaves = [] getDataLeaves data, [], leaves # We have e.g. `clients/overview` and `clients/foo/bar` now but we want # `clients` and `clients/foo` too. leavesIncludingBlocks = _.union leaves, (_.initial(p) for p in leaves) # There's a lot of duplicates now, let's remove them to speed things up. leavesIncludingBlocks = _.uniq leavesIncludingBlocks, (leafPath) -> _.pluck(leafPath, 'id').join ' ' # Blocks are supposed to be invisible. So lets remove them (otherwise we would # get paths with ids like `-- front --` and `-- back --`). leaves = _.map leavesIncludingBlocks, (path) -> return _.reject path, (node) -> node.isBlock # We might have gotten some empty paths, let's get rid of those. nonEmptyLeaves = _.filter leaves, (path) -> path.length > 0 nodesPaths = _.map nonEmptyLeaves, (leafPath) -> # `parts` will be the path to the new HTML page produced from the # markdown section. parts = _.union([dest], _.pluck(leafPath, 'id')) leafDest = fspath.join.apply @, parts leafDest = "#{leafDest}#{ext}" return [leafPath, leafDest] for [nodes, path] in nodesPaths mkdirp.sync fspath.dirname(path) # Let's create the actual HTML file now. grunt.file.copy tpl, path, process: (contents, path) -> html = grunt.template.process contents, data: _.extend({ section: _.last(nodes) ids: _.pluck(nodes, 'id') all: data root: nodes[0] }, _options.data) # Pretty print the html. return if _options.pretty then beautifyHTML(html) else html
true
# # grunt-md-templator # https://github.com/realyze/grunt-md-templator # # Copyright (c) 2013 PI:NAME:<NAME>END_PI # Licensed under the MIT license. # 'use strict' module.exports = (grunt) -> _ = require 'underscore' _s = require 'underscore.string' _.mixin(_s.exports()) {markdown} = require('markdown') beautifyHTML = require('js-beautify').html Entities = require('html-entities').AllHtmlEntities {decode} = new Entities() fspath = require 'path' mkdirp = require 'mkdirp' # Global options hash. _options = {} # Returns -1 if tag1 is less important than tag2, 0 if they're the same # and +1 if tag2 is more important. # The importance is based on the `options.tags` array. compareTags = (tag1, tag2) -> tagIndex = _.partial _.indexOf, _options.tags if tagIndex(tag1) > (tagIndex tag2) return -1 if tagIndex(tag1) == (tagIndex tag2) return 0 return 1 isBlockTag = (tag) -> tag.indexOf('block') == 0 getBlockName = (data) -> data[0][1].replace(/---\s*([^-\s]+)\s*---/, '$1') # Inserts a DOM region into the DOM region tree. insert = (data, root) -> tag = data[0][0] childTag = _.last _.pluck root.children, 'tag' # Handle blocks. Every block "inherits" heading level from # its parent header. Block ends when we either find a new block # tag or when the parent heading section ends. if isBlockTag(tag) if not root.tag? # It's the very first level of the tree, so just recurse in. return insert(data, _.last(root.children)) if childTag? and isBlockTag(childTag) # Current tag is a block and the last delimiter was a block => # end the previous block and start a new sibling block (with the # same heading level). tag = data[0][0] = childTag if _.isEmpty(root.children) # We've just found a new block without predecesors => start # a new block with parent heading level. tag = data[0][0] = "block-#{root.tag}" if _.isEmpty(root.children) or compareTags(tag, childTag) >= 0 # Note: The stringify/parse dance is necessary because renderJsonML is # changing data object. getHTML = (data) -> _.union(['html'], JSON.parse JSON.stringify data) metadata = getMetadata data root.children.push id: metadata.id metadata: metadata content: markdown.renderJsonML(getHTML data) header: markdown.renderJsonML(getHTML [data[0]]) body: markdown.renderJsonML(getHTML _.rest(data)) children: [] tag: tag isBlock: isBlockTag(tag) name: if isBlockTag(tag) then getBlockName(data) else null html: null # Filled later on. blocks: {} # Filled later on. if _options.decode # Make sure we decode the HTML entities. for attr in ['content', 'header', 'body'] _.last(root.children)[attr] = decode _.last(root.children)[attr] return root return insert(data, _.last(root.children)) processFile = (f) -> # Read'n'parse the md file. text = grunt.file.read f html = markdown.toHTMLTree markdown.parse text findDelimiter = (row) -> row[0] in _options.tags or (typeof(row[1]) is 'string' and row[1].match(/^---[^-]+---$/)) # Find all the relevant elements (i.e., headers) in JsonML. elemRows = _.filter html, _.isArray tagRows = _.filter elemRows, findDelimiter tagRows = _.map tagRows, (row) -> if typeof(row[1]) is 'string' and row[1].match(/^---[^-]+---$/) row[0] = 'block' return row blockTags = ("block-#{tag}" for tag in _options.tags) # ## Trick: # For every tag that creates scope, create it's block element child and # give one less priority level. # We use this to compare tag priorities (so that a block nested withing # an e.g. `h2` scope will have lower priority than `h2` but bigger than `h3`). _options.tags = _.flatten _.zip _options.tags, blockTags # ## Trick: # Add level-yet-to-be-determined block to the end of _options.tags (i.e., give # it the least priority). # That way it will always have a lower priority than any non-block tag we # find and hence will become it's child. _options.tags.push 'block' grunt.log.debug 'tagRows', tagRows grunt.log.debug '_options.tags', _options.tags # Parse the JsonML tree to get the "HTML regions" that correspond to each # header. Simply put, this splits the tree using 'h?' as separators). # # The idea here is that each header starts a new region and we want an # id for that region and the text before the next region starts. We'll # feed this info into the template and get a nice HTML partial. data = _.map tagRows, (tagRow, pos) -> index = _.indexOf html, tagRow next = tagRows[pos + 1] regionEnd = if next? then _.indexOf(html, next) else html.length return html.slice index, regionEnd root = {children: []} # Create the DOM region tree (we'll pass this tree to the # template later on). for d in data insert d, root root = findChildBlocks(root) root = findHTMLSubtrees(root) grunt.log.debug JSON.stringify root, null, 2 return root # DFS the tree and assign a `blocks` hash property to each node. The property # contains child nodes which are blocks. This is mainly for convenience so # that users can access the block by `node.blocks.<myBlockName>` shortcut. findChildBlocks = (root) -> root.blocks = {} for child in root.children findChildBlocks(child) if child.isBlock root.blocks[child.name] = child return root # DFS the tree and assign `html` property to each node. The property contains # the HTML content of the subtree (kind of like jQuery's `html()` method). findHTMLSubtrees = (root) -> for child in root.children findHTMLSubtrees(child) if root.children.length > 0 childHTML = _.pluck(root.children, 'html').join('') else childHTML = "" if root.isBlock # We're adding `body` for blocks because we don't want to include # the block element itself (which would happen if we included `content`). root.html = (root.body or '') + childHTML else root.html = (root.content or '') + childHTML root.html = _.trim(root.html) return root # Returns metadata for a region (accessible in the template). getMetadata = (data) -> grunt.log.debug 'data', data text = _.last data[0] {metadata_pattern} = _options match = text.match metadata_pattern metadata = {} if match # Strip the metadata pattern. data[0][data[0].length - 1] = _.trim text.replace(metadata_pattern, '') metadata = JSON.parse match[1] metadata.id or= _(data[0]).chain().last().slugify().value().toLowerCase() grunt.log.debug 'metadata', metadata return metadata grunt.registerMultiTask 'md_to_html', 'Turn markdown & template into HTML.', -> # Default options. _options = @options metadata_pattern: /{(.+)}/ tags: ['h1', 'h2', 'h3'] _.each @files, ({src, template, dest, ext}) => files = _.filter src, (filepath) -> if not grunt.file.exists filepath grunt.log.warn "Source file #{filepath} not found." return false return true # Parse the Markdown files specified in the currently processed # file dict. parsedFilesTuples = _.map files, (file) -> [file, processFile(file)] # Expand the specified template for each parsed file (with the data # compiled from the md file). _.each parsedFilesTuples, ([filepath, data]) -> tpl = template or _options.template if not _options.multiple_files grunt.file.copy tpl, dest, process: (contents, path) -> html = grunt.template.process contents, data: _.extend(data, _options.data) # Pretty print the html. return if _options.pretty then beautifyHTML(html) else html else splitIntoMultipleFiles(data, tpl, dest, ext) getDataLeaves = (data, pathToRoot=[], res) -> for child in data.children #parent = if data.id then [data.id] else [] getDataLeaves(child, _.union(pathToRoot, [data]), res) # Don't forget the leave node. pathToRoot.push(data) # We're only interested in the leaves. return unless _.isEmpty(data.children) # Forget the first part (that's the "header"). res.push _.rest(pathToRoot) # Creates multiple HTML files from `data`, each HTML file will be based on # template `tpl`, wil be stored in `dest` directory (plus the path determined # by the ids on the path to the section in the markdown document) and will # have `ext` extension. splitIntoMultipleFiles = (data, tpl, dest, ext) -> # Leaves is an array of arrays (paths from leaf to root in the markdown # document). leaves = [] getDataLeaves data, [], leaves # We have e.g. `clients/overview` and `clients/foo/bar` now but we want # `clients` and `clients/foo` too. leavesIncludingBlocks = _.union leaves, (_.initial(p) for p in leaves) # There's a lot of duplicates now, let's remove them to speed things up. leavesIncludingBlocks = _.uniq leavesIncludingBlocks, (leafPath) -> _.pluck(leafPath, 'id').join ' ' # Blocks are supposed to be invisible. So lets remove them (otherwise we would # get paths with ids like `-- front --` and `-- back --`). leaves = _.map leavesIncludingBlocks, (path) -> return _.reject path, (node) -> node.isBlock # We might have gotten some empty paths, let's get rid of those. nonEmptyLeaves = _.filter leaves, (path) -> path.length > 0 nodesPaths = _.map nonEmptyLeaves, (leafPath) -> # `parts` will be the path to the new HTML page produced from the # markdown section. parts = _.union([dest], _.pluck(leafPath, 'id')) leafDest = fspath.join.apply @, parts leafDest = "#{leafDest}#{ext}" return [leafPath, leafDest] for [nodes, path] in nodesPaths mkdirp.sync fspath.dirname(path) # Let's create the actual HTML file now. grunt.file.copy tpl, path, process: (contents, path) -> html = grunt.template.process contents, data: _.extend({ section: _.last(nodes) ids: _.pluck(nodes, 'id') all: data root: nodes[0] }, _options.data) # Pretty print the html. return if _options.pretty then beautifyHTML(html) else html
[ { "context": "et = '<keyboard cat>'\nexports.twitter =\n token :\"your token\"\n secret :\"your token secret\"\n", "end": 130, "score": 0.3674981892108917, "start": 126, "tag": "KEY", "value": "your" }, { "context": " '<keyboard cat>'\nexports.twitter =\n token :\"your token\"\n secret :\"your token secret\"\n", "end": 136, "score": 0.5269251465797424, "start": 131, "tag": "USERNAME", "value": "token" } ]
config-sample.coffee
mizchi/Wanderer
3
exports.domain = 'http://localhost' exports.port = 4444 exports.session_secret = '<keyboard cat>' exports.twitter = token :"your token" secret :"your token secret"
49471
exports.domain = 'http://localhost' exports.port = 4444 exports.session_secret = '<keyboard cat>' exports.twitter = token :"<KEY> token" secret :"your token secret"
true
exports.domain = 'http://localhost' exports.port = 4444 exports.session_secret = '<keyboard cat>' exports.twitter = token :"PI:KEY:<KEY>END_PI token" secret :"your token secret"
[ { "context": "enQuerying('project').respondWith [{\n Name: 'test Project'\n _ref: '/project/2'\n }]\n\n @_createApp", "end": 2463, "score": 0.8691965937614441, "start": 2451, "tag": "NAME", "value": "test Project" } ]
test/spec/portfoliohierarchy/PortfolioHierarchyAppSpec.coffee
rdayan1/app-catalog
0
Ext = window.Ext4 || window.Ext Ext.require [ 'Rally.app.Context' 'Rally.test.mock.data.WsapiModelFactory' 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp' ] describe 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', -> helpers _createApp: (settings) -> globalContext = Rally.environment.getContext() context = Ext.create 'Rally.app.Context', initialValues: project: globalContext.getProject() workspace: globalContext.getWorkspace() user: globalContext.getUser() subscription: globalContext.getSubscription() options = context: context renderTo: 'testDiv' if settings options.settings = settings @app = Ext.create 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', options @waitForComponentReady(@app) beforeEach -> Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager'] @userStoryModel = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel() @ajax.whenQuerying('typedefinition').respondWith [ Rally.test.mock.data.WsapiModelFactory.getModelDefinition('PortfolioItemProject') ] afterEach -> @app?.destroy() it 'test draws portfolio tree', -> interceptor = @ajax.whenQuerying('PortfolioItem/Project').respondWith [ {FormattedID: 'S1', ObjectID: '1', Name: 'Project 1'} ] @_createApp().then => sinon.assert.calledOnce(interceptor) expect(@app.query('rallyportfolioitemtreeitem').length).toBe 1 it 'test filter info displayed', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp().then => expect(@app.getEl().down('.filterInfo')).toBeInstanceOf Ext.Element it 'test project setting label is shown if following a specific project scope', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp( project: '/project/431439' ).then => @app.down('rallyfilterinfo').tooltip.show() tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0]) expect(tooltipContent.dom.innerHTML).toContain 'Project' expect(tooltipContent.dom.innerHTML).toContain 'Project 1' @app.down('rallyfilterinfo').tooltip.destroy() it 'test project setting label shows "Following Global Project Setting" if following global project scope', -> @ajax.whenQuerying('project').respondWith [{ Name: 'test Project' _ref: '/project/2' }] @_createApp().then => @app.down('rallyfilterinfo').tooltip.show() tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0]) expect(tooltipContent.dom.innerHTML).toContain 'Following Global Project Setting' @app.down('rallyfilterinfo').tooltip.destroy() it 'test help component is shown', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp().then => expect(@app).toHaveHelpComponent() it 'test empty query string does not create a filter', -> @_createApp( query: '' ).then => tree = @app.down('rallytree') expect(tree.topLevelStoreConfig.filters.length).toBe 0 it 'test non-empty query string creates a filter', -> @_createApp( query: '(Name = "blah")' ).then => tree = @app.down('rallytree') expect(tree.topLevelStoreConfig.filters.length).toBe 1 expect(tree.topLevelStoreConfig.filters[0].toString()).toEqual '(Name = "blah")' it 'should display an error message if you do not have RPM turned on ', -> Rally.environment.getContext().context.subscription.Modules = [] loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault' @_createApp().then => expect(loadSpy.callCount).toBe 0 expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription' it 'should set workspace on the tree config', -> @_createApp().then => tree = @app.down('rallytree') expect(tree.workspace._ref).toBe Rally.environment.getContext().getWorkspace()._ref it 'should add tooltip to schedule state read-only view for user story', -> @_createApp().then => tooltip = @app.tooltip expect(tooltip).not.toBeUndefined Ext.create 'Ext.Component', html: '<div class="schedule-state" state-data="Defined"</div>' renderTo: 'testDiv' tooltip.triggerElement = Ext.getBody().down('.schedule-state') tooltipUpdate = @spy tooltip, 'update' tooltip.show() expect(tooltipUpdate.callCount).toBe 1 expect(tooltipUpdate.calledWith('Defined')).toBeTruthy() it 'should destroy tooltip when app is destroyed', -> @_createApp().then => destroyTooltip = @spy @app.tooltip, 'destroy' @app.destroy() expect(destroyTooltip.callCount).toBe 1 describe 'should add boolean indicating if should call plan service for use in appsdk components lame lame lame', -> it 'should not retrieve data from plan service', -> @_createApp().then => tree = @app.down('rallytree') expect(tree.shouldRetrievePlanData).toBe false it 'should retrieve data from plan service', -> stub = @stub Rally.env.Context::, 'isFeatureEnabled' stub.withArgs("ROADMAP_PLANNING_PAGE").returns(true) @_createApp().then => tree = @app.down('rallytree') expect(tree.shouldRetrievePlanData).toBe true
199065
Ext = window.Ext4 || window.Ext Ext.require [ 'Rally.app.Context' 'Rally.test.mock.data.WsapiModelFactory' 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp' ] describe 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', -> helpers _createApp: (settings) -> globalContext = Rally.environment.getContext() context = Ext.create 'Rally.app.Context', initialValues: project: globalContext.getProject() workspace: globalContext.getWorkspace() user: globalContext.getUser() subscription: globalContext.getSubscription() options = context: context renderTo: 'testDiv' if settings options.settings = settings @app = Ext.create 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', options @waitForComponentReady(@app) beforeEach -> Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager'] @userStoryModel = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel() @ajax.whenQuerying('typedefinition').respondWith [ Rally.test.mock.data.WsapiModelFactory.getModelDefinition('PortfolioItemProject') ] afterEach -> @app?.destroy() it 'test draws portfolio tree', -> interceptor = @ajax.whenQuerying('PortfolioItem/Project').respondWith [ {FormattedID: 'S1', ObjectID: '1', Name: 'Project 1'} ] @_createApp().then => sinon.assert.calledOnce(interceptor) expect(@app.query('rallyportfolioitemtreeitem').length).toBe 1 it 'test filter info displayed', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp().then => expect(@app.getEl().down('.filterInfo')).toBeInstanceOf Ext.Element it 'test project setting label is shown if following a specific project scope', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp( project: '/project/431439' ).then => @app.down('rallyfilterinfo').tooltip.show() tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0]) expect(tooltipContent.dom.innerHTML).toContain 'Project' expect(tooltipContent.dom.innerHTML).toContain 'Project 1' @app.down('rallyfilterinfo').tooltip.destroy() it 'test project setting label shows "Following Global Project Setting" if following global project scope', -> @ajax.whenQuerying('project').respondWith [{ Name: '<NAME>' _ref: '/project/2' }] @_createApp().then => @app.down('rallyfilterinfo').tooltip.show() tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0]) expect(tooltipContent.dom.innerHTML).toContain 'Following Global Project Setting' @app.down('rallyfilterinfo').tooltip.destroy() it 'test help component is shown', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp().then => expect(@app).toHaveHelpComponent() it 'test empty query string does not create a filter', -> @_createApp( query: '' ).then => tree = @app.down('rallytree') expect(tree.topLevelStoreConfig.filters.length).toBe 0 it 'test non-empty query string creates a filter', -> @_createApp( query: '(Name = "blah")' ).then => tree = @app.down('rallytree') expect(tree.topLevelStoreConfig.filters.length).toBe 1 expect(tree.topLevelStoreConfig.filters[0].toString()).toEqual '(Name = "blah")' it 'should display an error message if you do not have RPM turned on ', -> Rally.environment.getContext().context.subscription.Modules = [] loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault' @_createApp().then => expect(loadSpy.callCount).toBe 0 expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription' it 'should set workspace on the tree config', -> @_createApp().then => tree = @app.down('rallytree') expect(tree.workspace._ref).toBe Rally.environment.getContext().getWorkspace()._ref it 'should add tooltip to schedule state read-only view for user story', -> @_createApp().then => tooltip = @app.tooltip expect(tooltip).not.toBeUndefined Ext.create 'Ext.Component', html: '<div class="schedule-state" state-data="Defined"</div>' renderTo: 'testDiv' tooltip.triggerElement = Ext.getBody().down('.schedule-state') tooltipUpdate = @spy tooltip, 'update' tooltip.show() expect(tooltipUpdate.callCount).toBe 1 expect(tooltipUpdate.calledWith('Defined')).toBeTruthy() it 'should destroy tooltip when app is destroyed', -> @_createApp().then => destroyTooltip = @spy @app.tooltip, 'destroy' @app.destroy() expect(destroyTooltip.callCount).toBe 1 describe 'should add boolean indicating if should call plan service for use in appsdk components lame lame lame', -> it 'should not retrieve data from plan service', -> @_createApp().then => tree = @app.down('rallytree') expect(tree.shouldRetrievePlanData).toBe false it 'should retrieve data from plan service', -> stub = @stub Rally.env.Context::, 'isFeatureEnabled' stub.withArgs("ROADMAP_PLANNING_PAGE").returns(true) @_createApp().then => tree = @app.down('rallytree') expect(tree.shouldRetrievePlanData).toBe true
true
Ext = window.Ext4 || window.Ext Ext.require [ 'Rally.app.Context' 'Rally.test.mock.data.WsapiModelFactory' 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp' ] describe 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', -> helpers _createApp: (settings) -> globalContext = Rally.environment.getContext() context = Ext.create 'Rally.app.Context', initialValues: project: globalContext.getProject() workspace: globalContext.getWorkspace() user: globalContext.getUser() subscription: globalContext.getSubscription() options = context: context renderTo: 'testDiv' if settings options.settings = settings @app = Ext.create 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', options @waitForComponentReady(@app) beforeEach -> Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager'] @userStoryModel = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel() @ajax.whenQuerying('typedefinition').respondWith [ Rally.test.mock.data.WsapiModelFactory.getModelDefinition('PortfolioItemProject') ] afterEach -> @app?.destroy() it 'test draws portfolio tree', -> interceptor = @ajax.whenQuerying('PortfolioItem/Project').respondWith [ {FormattedID: 'S1', ObjectID: '1', Name: 'Project 1'} ] @_createApp().then => sinon.assert.calledOnce(interceptor) expect(@app.query('rallyportfolioitemtreeitem').length).toBe 1 it 'test filter info displayed', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp().then => expect(@app.getEl().down('.filterInfo')).toBeInstanceOf Ext.Element it 'test project setting label is shown if following a specific project scope', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp( project: '/project/431439' ).then => @app.down('rallyfilterinfo').tooltip.show() tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0]) expect(tooltipContent.dom.innerHTML).toContain 'Project' expect(tooltipContent.dom.innerHTML).toContain 'Project 1' @app.down('rallyfilterinfo').tooltip.destroy() it 'test project setting label shows "Following Global Project Setting" if following global project scope', -> @ajax.whenQuerying('project').respondWith [{ Name: 'PI:NAME:<NAME>END_PI' _ref: '/project/2' }] @_createApp().then => @app.down('rallyfilterinfo').tooltip.show() tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0]) expect(tooltipContent.dom.innerHTML).toContain 'Following Global Project Setting' @app.down('rallyfilterinfo').tooltip.destroy() it 'test help component is shown', -> @ajax.whenQuerying('PortfolioItem/Project').respondWith() @_createApp().then => expect(@app).toHaveHelpComponent() it 'test empty query string does not create a filter', -> @_createApp( query: '' ).then => tree = @app.down('rallytree') expect(tree.topLevelStoreConfig.filters.length).toBe 0 it 'test non-empty query string creates a filter', -> @_createApp( query: '(Name = "blah")' ).then => tree = @app.down('rallytree') expect(tree.topLevelStoreConfig.filters.length).toBe 1 expect(tree.topLevelStoreConfig.filters[0].toString()).toEqual '(Name = "blah")' it 'should display an error message if you do not have RPM turned on ', -> Rally.environment.getContext().context.subscription.Modules = [] loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault' @_createApp().then => expect(loadSpy.callCount).toBe 0 expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription' it 'should set workspace on the tree config', -> @_createApp().then => tree = @app.down('rallytree') expect(tree.workspace._ref).toBe Rally.environment.getContext().getWorkspace()._ref it 'should add tooltip to schedule state read-only view for user story', -> @_createApp().then => tooltip = @app.tooltip expect(tooltip).not.toBeUndefined Ext.create 'Ext.Component', html: '<div class="schedule-state" state-data="Defined"</div>' renderTo: 'testDiv' tooltip.triggerElement = Ext.getBody().down('.schedule-state') tooltipUpdate = @spy tooltip, 'update' tooltip.show() expect(tooltipUpdate.callCount).toBe 1 expect(tooltipUpdate.calledWith('Defined')).toBeTruthy() it 'should destroy tooltip when app is destroyed', -> @_createApp().then => destroyTooltip = @spy @app.tooltip, 'destroy' @app.destroy() expect(destroyTooltip.callCount).toBe 1 describe 'should add boolean indicating if should call plan service for use in appsdk components lame lame lame', -> it 'should not retrieve data from plan service', -> @_createApp().then => tree = @app.down('rallytree') expect(tree.shouldRetrievePlanData).toBe false it 'should retrieve data from plan service', -> stub = @stub Rally.env.Context::, 'isFeatureEnabled' stub.withArgs("ROADMAP_PLANNING_PAGE").returns(true) @_createApp().then => tree = @app.down('rallytree') expect(tree.shouldRetrievePlanData).toBe true
[ { "context": " id: 1\n name: 'Translation manager'\n prefixNamespace: ''\n defaultLa", "end": 106, "score": 0.789883553981781, "start": 95, "tag": "NAME", "value": "Translation" }, { "context": " id: 2\n name: 'Sample project'\n prefixNamespace: ''\n defaultLanguageId", "end": 428, "score": 0.740911602973938, "start": 414, "tag": "NAME", "value": "Sample project" } ]
server/db/seeds/development/000006-project.coffee
Contactis/translation-manager
0
moment = require 'moment' projects = [ { id: 1 name: 'Translation manager' prefixNamespace: '' defaultLanguageId: 1 description: 'This is dummy description for translation manager' isDeleted: 0 createdAt: moment().format() updatedAt: moment().format() } { id: 2 name: 'Sample project' prefixNamespace: '' defaultLanguageId: 3 description: 'The purpus of this project is to test the API' isDeleted: 0 createdAt: moment().format() updatedAt: moment().format() } ] projects.forEach (value, i) -> Project.seed value
207393
moment = require 'moment' projects = [ { id: 1 name: '<NAME> manager' prefixNamespace: '' defaultLanguageId: 1 description: 'This is dummy description for translation manager' isDeleted: 0 createdAt: moment().format() updatedAt: moment().format() } { id: 2 name: '<NAME>' prefixNamespace: '' defaultLanguageId: 3 description: 'The purpus of this project is to test the API' isDeleted: 0 createdAt: moment().format() updatedAt: moment().format() } ] projects.forEach (value, i) -> Project.seed value
true
moment = require 'moment' projects = [ { id: 1 name: 'PI:NAME:<NAME>END_PI manager' prefixNamespace: '' defaultLanguageId: 1 description: 'This is dummy description for translation manager' isDeleted: 0 createdAt: moment().format() updatedAt: moment().format() } { id: 2 name: 'PI:NAME:<NAME>END_PI' prefixNamespace: '' defaultLanguageId: 3 description: 'The purpus of this project is to test the API' isDeleted: 0 createdAt: moment().format() updatedAt: moment().format() } ] projects.forEach (value, i) -> Project.seed value
[ { "context": "###\n backbone-orm.js 0.5.12\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n Lice", "end": 58, "score": 0.9989747405052185, "start": 50, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n License: MIT (http://www.opensourc", "end": 88, "score": 0.9997296929359436, "start": 80, "tag": "USERNAME", "value": "vidigami" } ]
src/relations/many.coffee
michaelBenin/backbone-orm
1
### backbone-orm.js 0.5.12 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### Backbone = require 'backbone' _ = require 'underscore' inflection = require 'inflection' Queue = require '../queue' Utils = require '../utils' # @private module.exports = class Many extends require('./relation') constructor: (@model_type, @key, options) -> @[key] = value for key, value of options @virtual_id_accessor or= "#{inflection.singularize(@key)}_ids" @join_key = @foreign_key or inflection.foreign_key(@model_type.model_name) unless @join_key @foreign_key = inflection.foreign_key(@as or @model_type.model_name) unless @foreign_key unless @collection_type # @private class Collection extends Backbone.Collection model: @reverse_model_type @collection_type = Collection initialize: -> @reverse_relation = @_findOrGenerateReverseRelation(@) throw new Error "Both relationship directions cannot embed (#{@model_type.model_name} and #{@reverse_model_type.model_name}). Choose one or the other." if @embed and @reverse_relation and @reverse_relation.embed throw new Error "The reverse of a hasMany relation should be `belongsTo`, not `hasOne` (#{@model_type.model_name} and #{@reverse_model_type.model_name})." if @reverse_relation?.type is 'hasOne' # check for join table @join_table = @findOrGenerateJoinTable(@) if @reverse_relation.type is 'hasMany' initializeModel: (model) -> model.setLoaded(@key, false) unless model.isLoadedExists(@key) # it may have been set before initialize is called @_bindBacklinks(model) releaseModel: (model) -> @_unbindBacklinks(model) delete model._orm set: (model, key, value, options) -> throw new Error "Many.set: Unexpected key #{key}. Expecting: #{@key} or #{@virtual_id_accessor} or #{@foreign_key}" unless ((key is @key) or (key is @virtual_id_accessor) or (key is @foreign_key)) collection = @_bindBacklinks(model) value = value.models if Utils.isCollection(value) value = [] if _.isUndefined(value) # Backbone clear or reset throw new Error "HasMany.set: Unexpected type to set #{key}. Expecting array: #{Utils.inspect(value)}" unless _.isArray(value) Utils.orSet(model, 'rel_dirty', {})[@key] = true model.setLoaded(@key, _.all(value, (item) -> Utils.dataId(item) isnt item)) # set the collection with found or created models models = ((if related_model = collection.get(Utils.dataId(item)) then Utils.updateModel(related_model, item) else Utils.updateOrNew(item, @reverse_model_type)) for item in value) model.setLoaded(@key, _.all(models, (model) -> model.isLoaded())) previous_models = _.clone(collection.models) collection.reset(models) if @reverse_relation.type is 'belongsTo' model_ids = _.pluck(models, 'id') related_model.set(@foreign_key, null) for related_model in previous_models when not _.contains(model_ids, related_model.id) return @ get: (model, key, callback) -> throw new Error "Many.get: Unexpected key #{key}. Expecting: #{@key} or #{@virtual_id_accessor} or #{@foreign_key}" unless ((key is @key) or (key is @virtual_id_accessor) or (key is @foreign_key)) collection = @_ensureCollection(model) returnValue = => return if key is @virtual_id_accessor then (related_model.id for related_model in collection.models) else collection # asynchronous path, needs load if callback and not @isVirtual() and not @manual_fetch and not (is_loaded = model.isLoaded(@key)) # fetch @cursor(model, @key).toJSON (err, json) => return callback(err) if err model.setLoaded(@key, true) # process the found models for model_json in json if related_model = collection.get(model_json[@reverse_model_type::idAttribute]) related_model.set(model_json) else collection.add(related_model = Utils.updateOrNew(model_json, @reverse_model_type)) # update cache (cache.set(related_model.id, related_model) for related_model in collection.models) if cache = @reverse_model_type.cache result = returnValue() callback(null, if result.models then result.models else result) # synchronous path result = returnValue() callback(null, if result.models then result.models else result) if callback and (is_loaded or @manual_fetch) return result save: (model, callback) -> return callback() if not @_hasChanged(model) delete Utils.orSet(model, 'rel_dirty', {})[@key] collection = @_ensureCollection(model) @_saveRelated(model, _.clone(collection.models), callback) appendJSON: (json, model) -> return if @isVirtual() # skip virtual attributes collection = @_ensureCollection(model) json_key = if @embed then @key else @virtual_id_accessor return json[json_key] = collection.toJSON() if @embed add: (model, related_model) -> collection = @_ensureCollection(model) current_related_model = collection.get(related_model.id) return if current_related_model is related_model # TODO: this is needed for model lifecycle - not knowing when a model is actually disposed and not wanting to remove a model from a relationship # throw new Error "\nModel added twice: #{Utils.inspect(current_related_model)}\nand\n#{Utils.inspect(related_model)}" if current_related_model collection.remove(current_related_model) if current_related_model @reverse_model_type.cache.set(related_model.id, related_model) if @reverse_model_type.cache and related_model.id # make sure the latest model is in the cache collection.add(related_model) remove: (model, related_model) -> collection = @_ensureCollection(model) return unless current_related_model = collection.get(related_model.id) collection.remove(current_related_model) patchAdd: (model, relateds, callback) -> return callback(new Error "Many.patchAdd: model has null id for: #{@key}") unless model.id return callback(new Error "Many.patchAdd: missing model for: #{@key}") unless relateds relateds = [relateds] unless _.isArray(relateds) collection = @_ensureCollection(model) relateds = ((if related_model = collection.get(Utils.dataId(item)) then Utils.updateModel(related_model, item) else Utils.updateOrNew(item, @reverse_model_type)) for item in relateds) related_ids = (Utils.dataId(related) for related in relateds) collection.add(relateds) if model.isLoaded(@key) # check for needing load (model.setLoaded(@key, false); break) for related in relateds when not related.isLoaded() # patch in store if @join_table queue = new Queue(1) for related_id in related_ids do (related_id) => queue.defer (callback) => return callback(new Error "Many.patchAdd: cannot add an new model. Please save first.") unless related_id add = (callback) => attributes = {} attributes[@foreign_key] = model.id attributes[@reverse_relation.foreign_key] = related_id # console.log "Creating join for: #{@model_type.model_name} join: #{Utils.inspect(attributes)}" join = new @join_table(attributes) join.save callback # just create another entry return add(callback) if @reverse_relation.type is 'hasMany' # check for changes (query = {})[@reverse_relation.foreign_key] = related_id return @join_table.find query, (err, join_table_json) => return callback(err) if err return add(callback) unless join_table_json # create a new join table entry return callback() if join_table_json[@foreign_key] is model.id # already related # update existing relationship join_table_json[@foreign_key] = model.id Utils.modelJSONSave(join_table_json, @join_table, callback) queue.await callback else query = {id: $in: related_ids} @reverse_model_type.cursor(query).toJSON (err, related_jsons) => queue = new Queue(1) for related_json in related_jsons do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = model.id Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback patchRemove: (model, relateds, callback) -> return callback(new Error "Many.patchRemove: model has null id for: #{@key}") unless model.id # REMOVE ALL if arguments.length is 2 callback = relateds return callback() if not @reverse_relation if Utils.isModel(model) delete Utils.orSet(model, 'rel_dirty', {})[@key] collection = @_ensureCollection(model) related_models = _.clone(collection.models) else related_models = (new @reverse_model_type(json) for json in (model[@key] or [])) # clear in memory for related_model in related_models related_model.set(@foreign_key, null) cache.set(related_model.id, related_model) if cache = related_model.cache() # ensure the cache is up-to-date # clear in store through join table if @join_table (query = {})[@join_key] = model.id return @join_table.destroy(query, callback) # clear back links on models and save else (query = {})[@reverse_relation.foreign_key] = model.id @reverse_model_type.cursor(query).toJSON (err, json) => return callback(err) if err # clear reverses queue = new Queue(1) for related_json in json do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = null Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback return # REMOVE SOME return callback(new Error('Many.patchRemove: embedded relationships are not supported')) if @isEmbedded() return callback(new Error('One.patchRemove: missing model for remove')) unless relateds relateds = [relateds] unless _.isArray(relateds) collection = @_ensureCollection(model) # destroy in memory for related in relateds for current_related_model in collection.models (collection.remove(current_related_model); break) if Utils.dataIsSameModel(current_related_model, related) # a match related_ids = (Utils.dataId(related) for related in relateds) # clear in store through join table if @join_table # can directly destroy the join table entry query = {} query[@join_key] = model.id query[@reverse_relation.join_key] = {$in: related_ids} @join_table.destroy query, callback # clear back links on models and save else query = {} query[@reverse_relation.foreign_key] = model.id query.id = {$in: related_ids} @reverse_model_type.cursor(query).toJSON (err, json) => return callback(err) if err # clear reverses queue = new Queue(1) for related_json in json do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = null Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback cursor: (model, key, query) -> json = if Utils.isModel(model) then model.attributes else model (query = _.clone(query or {}))[if @join_table then @join_key else @reverse_relation.foreign_key] = json[@model_type::idAttribute] (query.$values or= []).push('id') if key is @virtual_id_accessor return @reverse_model_type.cursor(query) #################################### # Internal #################################### _bindBacklinks: (model) -> return collection if (collection = model.attributes[@key]) instanceof @collection_type collection = model.attributes[@key] = new @collection_type() return collection unless @reverse_relation # no back links events = Utils.set(collection, 'events', {}) events.add = (related_model) => if @reverse_relation.add @reverse_relation.add(related_model, model) else current_model = related_model.get(@reverse_relation.key) is_current = model.id and (Utils.dataId(current_model) is model.id) related_model.set(@reverse_relation.key, model) if not is_current or (is_current and not current_model.isLoaded()) events.remove = (related_model) => if @reverse_relation.remove @reverse_relation.remove(related_model, model) else current_model = related_model.get(@reverse_relation.key) related_model.set(@reverse_relation.key, null) if Utils.dataId(current_model) is model.id events.reset = (collection, options) => current_models = collection.models previous_models = options.previousModels or [] changes = _.groupBy(previous_models, (test) -> if !!_.find(current_models, (current_model) -> current_model.id is test.id) then 'kept' else 'removed') added = if changes.kept then _.select(current_models, (test) -> !_.find(changes.kept, (keep_model) -> keep_model.id is test.id)) else current_models # update back links (events.remove(related_model) for related_model in changes.removed) if changes.removed (events.add(related_model) for related_model in added) collection.on(method, events[method]) for method in ['add', 'remove', 'reset'] # bind return collection _unbindBacklinks: (model) -> return unless events = Utils.get(model, 'events') # already unbound Utils.unset(model, 'events') collection = model.attributes[@key] collection.models.splice() events = _.clone() for method in ['add', 'remove', 'reset'] # unbind collection.off(method, events[method]) events[method] = null return _ensureCollection: (model) -> return @_bindBacklinks(model) _hasChanged: (model) -> return !!Utils.orSet(model, 'rel_dirty', {})[@key] or model.hasChanged(@key) return false unless @reverse_relation collection = @_ensureCollection(model) return true for model in model.models when model.hasChanged(@reverse_relation.foreign_key) return false
167
### backbone-orm.js 0.5.12 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### Backbone = require 'backbone' _ = require 'underscore' inflection = require 'inflection' Queue = require '../queue' Utils = require '../utils' # @private module.exports = class Many extends require('./relation') constructor: (@model_type, @key, options) -> @[key] = value for key, value of options @virtual_id_accessor or= "#{inflection.singularize(@key)}_ids" @join_key = @foreign_key or inflection.foreign_key(@model_type.model_name) unless @join_key @foreign_key = inflection.foreign_key(@as or @model_type.model_name) unless @foreign_key unless @collection_type # @private class Collection extends Backbone.Collection model: @reverse_model_type @collection_type = Collection initialize: -> @reverse_relation = @_findOrGenerateReverseRelation(@) throw new Error "Both relationship directions cannot embed (#{@model_type.model_name} and #{@reverse_model_type.model_name}). Choose one or the other." if @embed and @reverse_relation and @reverse_relation.embed throw new Error "The reverse of a hasMany relation should be `belongsTo`, not `hasOne` (#{@model_type.model_name} and #{@reverse_model_type.model_name})." if @reverse_relation?.type is 'hasOne' # check for join table @join_table = @findOrGenerateJoinTable(@) if @reverse_relation.type is 'hasMany' initializeModel: (model) -> model.setLoaded(@key, false) unless model.isLoadedExists(@key) # it may have been set before initialize is called @_bindBacklinks(model) releaseModel: (model) -> @_unbindBacklinks(model) delete model._orm set: (model, key, value, options) -> throw new Error "Many.set: Unexpected key #{key}. Expecting: #{@key} or #{@virtual_id_accessor} or #{@foreign_key}" unless ((key is @key) or (key is @virtual_id_accessor) or (key is @foreign_key)) collection = @_bindBacklinks(model) value = value.models if Utils.isCollection(value) value = [] if _.isUndefined(value) # Backbone clear or reset throw new Error "HasMany.set: Unexpected type to set #{key}. Expecting array: #{Utils.inspect(value)}" unless _.isArray(value) Utils.orSet(model, 'rel_dirty', {})[@key] = true model.setLoaded(@key, _.all(value, (item) -> Utils.dataId(item) isnt item)) # set the collection with found or created models models = ((if related_model = collection.get(Utils.dataId(item)) then Utils.updateModel(related_model, item) else Utils.updateOrNew(item, @reverse_model_type)) for item in value) model.setLoaded(@key, _.all(models, (model) -> model.isLoaded())) previous_models = _.clone(collection.models) collection.reset(models) if @reverse_relation.type is 'belongsTo' model_ids = _.pluck(models, 'id') related_model.set(@foreign_key, null) for related_model in previous_models when not _.contains(model_ids, related_model.id) return @ get: (model, key, callback) -> throw new Error "Many.get: Unexpected key #{key}. Expecting: #{@key} or #{@virtual_id_accessor} or #{@foreign_key}" unless ((key is @key) or (key is @virtual_id_accessor) or (key is @foreign_key)) collection = @_ensureCollection(model) returnValue = => return if key is @virtual_id_accessor then (related_model.id for related_model in collection.models) else collection # asynchronous path, needs load if callback and not @isVirtual() and not @manual_fetch and not (is_loaded = model.isLoaded(@key)) # fetch @cursor(model, @key).toJSON (err, json) => return callback(err) if err model.setLoaded(@key, true) # process the found models for model_json in json if related_model = collection.get(model_json[@reverse_model_type::idAttribute]) related_model.set(model_json) else collection.add(related_model = Utils.updateOrNew(model_json, @reverse_model_type)) # update cache (cache.set(related_model.id, related_model) for related_model in collection.models) if cache = @reverse_model_type.cache result = returnValue() callback(null, if result.models then result.models else result) # synchronous path result = returnValue() callback(null, if result.models then result.models else result) if callback and (is_loaded or @manual_fetch) return result save: (model, callback) -> return callback() if not @_hasChanged(model) delete Utils.orSet(model, 'rel_dirty', {})[@key] collection = @_ensureCollection(model) @_saveRelated(model, _.clone(collection.models), callback) appendJSON: (json, model) -> return if @isVirtual() # skip virtual attributes collection = @_ensureCollection(model) json_key = if @embed then @key else @virtual_id_accessor return json[json_key] = collection.toJSON() if @embed add: (model, related_model) -> collection = @_ensureCollection(model) current_related_model = collection.get(related_model.id) return if current_related_model is related_model # TODO: this is needed for model lifecycle - not knowing when a model is actually disposed and not wanting to remove a model from a relationship # throw new Error "\nModel added twice: #{Utils.inspect(current_related_model)}\nand\n#{Utils.inspect(related_model)}" if current_related_model collection.remove(current_related_model) if current_related_model @reverse_model_type.cache.set(related_model.id, related_model) if @reverse_model_type.cache and related_model.id # make sure the latest model is in the cache collection.add(related_model) remove: (model, related_model) -> collection = @_ensureCollection(model) return unless current_related_model = collection.get(related_model.id) collection.remove(current_related_model) patchAdd: (model, relateds, callback) -> return callback(new Error "Many.patchAdd: model has null id for: #{@key}") unless model.id return callback(new Error "Many.patchAdd: missing model for: #{@key}") unless relateds relateds = [relateds] unless _.isArray(relateds) collection = @_ensureCollection(model) relateds = ((if related_model = collection.get(Utils.dataId(item)) then Utils.updateModel(related_model, item) else Utils.updateOrNew(item, @reverse_model_type)) for item in relateds) related_ids = (Utils.dataId(related) for related in relateds) collection.add(relateds) if model.isLoaded(@key) # check for needing load (model.setLoaded(@key, false); break) for related in relateds when not related.isLoaded() # patch in store if @join_table queue = new Queue(1) for related_id in related_ids do (related_id) => queue.defer (callback) => return callback(new Error "Many.patchAdd: cannot add an new model. Please save first.") unless related_id add = (callback) => attributes = {} attributes[@foreign_key] = model.id attributes[@reverse_relation.foreign_key] = related_id # console.log "Creating join for: #{@model_type.model_name} join: #{Utils.inspect(attributes)}" join = new @join_table(attributes) join.save callback # just create another entry return add(callback) if @reverse_relation.type is 'hasMany' # check for changes (query = {})[@reverse_relation.foreign_key] = related_id return @join_table.find query, (err, join_table_json) => return callback(err) if err return add(callback) unless join_table_json # create a new join table entry return callback() if join_table_json[@foreign_key] is model.id # already related # update existing relationship join_table_json[@foreign_key] = model.id Utils.modelJSONSave(join_table_json, @join_table, callback) queue.await callback else query = {id: $in: related_ids} @reverse_model_type.cursor(query).toJSON (err, related_jsons) => queue = new Queue(1) for related_json in related_jsons do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = model.id Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback patchRemove: (model, relateds, callback) -> return callback(new Error "Many.patchRemove: model has null id for: #{@key}") unless model.id # REMOVE ALL if arguments.length is 2 callback = relateds return callback() if not @reverse_relation if Utils.isModel(model) delete Utils.orSet(model, 'rel_dirty', {})[@key] collection = @_ensureCollection(model) related_models = _.clone(collection.models) else related_models = (new @reverse_model_type(json) for json in (model[@key] or [])) # clear in memory for related_model in related_models related_model.set(@foreign_key, null) cache.set(related_model.id, related_model) if cache = related_model.cache() # ensure the cache is up-to-date # clear in store through join table if @join_table (query = {})[@join_key] = model.id return @join_table.destroy(query, callback) # clear back links on models and save else (query = {})[@reverse_relation.foreign_key] = model.id @reverse_model_type.cursor(query).toJSON (err, json) => return callback(err) if err # clear reverses queue = new Queue(1) for related_json in json do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = null Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback return # REMOVE SOME return callback(new Error('Many.patchRemove: embedded relationships are not supported')) if @isEmbedded() return callback(new Error('One.patchRemove: missing model for remove')) unless relateds relateds = [relateds] unless _.isArray(relateds) collection = @_ensureCollection(model) # destroy in memory for related in relateds for current_related_model in collection.models (collection.remove(current_related_model); break) if Utils.dataIsSameModel(current_related_model, related) # a match related_ids = (Utils.dataId(related) for related in relateds) # clear in store through join table if @join_table # can directly destroy the join table entry query = {} query[@join_key] = model.id query[@reverse_relation.join_key] = {$in: related_ids} @join_table.destroy query, callback # clear back links on models and save else query = {} query[@reverse_relation.foreign_key] = model.id query.id = {$in: related_ids} @reverse_model_type.cursor(query).toJSON (err, json) => return callback(err) if err # clear reverses queue = new Queue(1) for related_json in json do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = null Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback cursor: (model, key, query) -> json = if Utils.isModel(model) then model.attributes else model (query = _.clone(query or {}))[if @join_table then @join_key else @reverse_relation.foreign_key] = json[@model_type::idAttribute] (query.$values or= []).push('id') if key is @virtual_id_accessor return @reverse_model_type.cursor(query) #################################### # Internal #################################### _bindBacklinks: (model) -> return collection if (collection = model.attributes[@key]) instanceof @collection_type collection = model.attributes[@key] = new @collection_type() return collection unless @reverse_relation # no back links events = Utils.set(collection, 'events', {}) events.add = (related_model) => if @reverse_relation.add @reverse_relation.add(related_model, model) else current_model = related_model.get(@reverse_relation.key) is_current = model.id and (Utils.dataId(current_model) is model.id) related_model.set(@reverse_relation.key, model) if not is_current or (is_current and not current_model.isLoaded()) events.remove = (related_model) => if @reverse_relation.remove @reverse_relation.remove(related_model, model) else current_model = related_model.get(@reverse_relation.key) related_model.set(@reverse_relation.key, null) if Utils.dataId(current_model) is model.id events.reset = (collection, options) => current_models = collection.models previous_models = options.previousModels or [] changes = _.groupBy(previous_models, (test) -> if !!_.find(current_models, (current_model) -> current_model.id is test.id) then 'kept' else 'removed') added = if changes.kept then _.select(current_models, (test) -> !_.find(changes.kept, (keep_model) -> keep_model.id is test.id)) else current_models # update back links (events.remove(related_model) for related_model in changes.removed) if changes.removed (events.add(related_model) for related_model in added) collection.on(method, events[method]) for method in ['add', 'remove', 'reset'] # bind return collection _unbindBacklinks: (model) -> return unless events = Utils.get(model, 'events') # already unbound Utils.unset(model, 'events') collection = model.attributes[@key] collection.models.splice() events = _.clone() for method in ['add', 'remove', 'reset'] # unbind collection.off(method, events[method]) events[method] = null return _ensureCollection: (model) -> return @_bindBacklinks(model) _hasChanged: (model) -> return !!Utils.orSet(model, 'rel_dirty', {})[@key] or model.hasChanged(@key) return false unless @reverse_relation collection = @_ensureCollection(model) return true for model in model.models when model.hasChanged(@reverse_relation.foreign_key) return false
true
### backbone-orm.js 0.5.12 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### Backbone = require 'backbone' _ = require 'underscore' inflection = require 'inflection' Queue = require '../queue' Utils = require '../utils' # @private module.exports = class Many extends require('./relation') constructor: (@model_type, @key, options) -> @[key] = value for key, value of options @virtual_id_accessor or= "#{inflection.singularize(@key)}_ids" @join_key = @foreign_key or inflection.foreign_key(@model_type.model_name) unless @join_key @foreign_key = inflection.foreign_key(@as or @model_type.model_name) unless @foreign_key unless @collection_type # @private class Collection extends Backbone.Collection model: @reverse_model_type @collection_type = Collection initialize: -> @reverse_relation = @_findOrGenerateReverseRelation(@) throw new Error "Both relationship directions cannot embed (#{@model_type.model_name} and #{@reverse_model_type.model_name}). Choose one or the other." if @embed and @reverse_relation and @reverse_relation.embed throw new Error "The reverse of a hasMany relation should be `belongsTo`, not `hasOne` (#{@model_type.model_name} and #{@reverse_model_type.model_name})." if @reverse_relation?.type is 'hasOne' # check for join table @join_table = @findOrGenerateJoinTable(@) if @reverse_relation.type is 'hasMany' initializeModel: (model) -> model.setLoaded(@key, false) unless model.isLoadedExists(@key) # it may have been set before initialize is called @_bindBacklinks(model) releaseModel: (model) -> @_unbindBacklinks(model) delete model._orm set: (model, key, value, options) -> throw new Error "Many.set: Unexpected key #{key}. Expecting: #{@key} or #{@virtual_id_accessor} or #{@foreign_key}" unless ((key is @key) or (key is @virtual_id_accessor) or (key is @foreign_key)) collection = @_bindBacklinks(model) value = value.models if Utils.isCollection(value) value = [] if _.isUndefined(value) # Backbone clear or reset throw new Error "HasMany.set: Unexpected type to set #{key}. Expecting array: #{Utils.inspect(value)}" unless _.isArray(value) Utils.orSet(model, 'rel_dirty', {})[@key] = true model.setLoaded(@key, _.all(value, (item) -> Utils.dataId(item) isnt item)) # set the collection with found or created models models = ((if related_model = collection.get(Utils.dataId(item)) then Utils.updateModel(related_model, item) else Utils.updateOrNew(item, @reverse_model_type)) for item in value) model.setLoaded(@key, _.all(models, (model) -> model.isLoaded())) previous_models = _.clone(collection.models) collection.reset(models) if @reverse_relation.type is 'belongsTo' model_ids = _.pluck(models, 'id') related_model.set(@foreign_key, null) for related_model in previous_models when not _.contains(model_ids, related_model.id) return @ get: (model, key, callback) -> throw new Error "Many.get: Unexpected key #{key}. Expecting: #{@key} or #{@virtual_id_accessor} or #{@foreign_key}" unless ((key is @key) or (key is @virtual_id_accessor) or (key is @foreign_key)) collection = @_ensureCollection(model) returnValue = => return if key is @virtual_id_accessor then (related_model.id for related_model in collection.models) else collection # asynchronous path, needs load if callback and not @isVirtual() and not @manual_fetch and not (is_loaded = model.isLoaded(@key)) # fetch @cursor(model, @key).toJSON (err, json) => return callback(err) if err model.setLoaded(@key, true) # process the found models for model_json in json if related_model = collection.get(model_json[@reverse_model_type::idAttribute]) related_model.set(model_json) else collection.add(related_model = Utils.updateOrNew(model_json, @reverse_model_type)) # update cache (cache.set(related_model.id, related_model) for related_model in collection.models) if cache = @reverse_model_type.cache result = returnValue() callback(null, if result.models then result.models else result) # synchronous path result = returnValue() callback(null, if result.models then result.models else result) if callback and (is_loaded or @manual_fetch) return result save: (model, callback) -> return callback() if not @_hasChanged(model) delete Utils.orSet(model, 'rel_dirty', {})[@key] collection = @_ensureCollection(model) @_saveRelated(model, _.clone(collection.models), callback) appendJSON: (json, model) -> return if @isVirtual() # skip virtual attributes collection = @_ensureCollection(model) json_key = if @embed then @key else @virtual_id_accessor return json[json_key] = collection.toJSON() if @embed add: (model, related_model) -> collection = @_ensureCollection(model) current_related_model = collection.get(related_model.id) return if current_related_model is related_model # TODO: this is needed for model lifecycle - not knowing when a model is actually disposed and not wanting to remove a model from a relationship # throw new Error "\nModel added twice: #{Utils.inspect(current_related_model)}\nand\n#{Utils.inspect(related_model)}" if current_related_model collection.remove(current_related_model) if current_related_model @reverse_model_type.cache.set(related_model.id, related_model) if @reverse_model_type.cache and related_model.id # make sure the latest model is in the cache collection.add(related_model) remove: (model, related_model) -> collection = @_ensureCollection(model) return unless current_related_model = collection.get(related_model.id) collection.remove(current_related_model) patchAdd: (model, relateds, callback) -> return callback(new Error "Many.patchAdd: model has null id for: #{@key}") unless model.id return callback(new Error "Many.patchAdd: missing model for: #{@key}") unless relateds relateds = [relateds] unless _.isArray(relateds) collection = @_ensureCollection(model) relateds = ((if related_model = collection.get(Utils.dataId(item)) then Utils.updateModel(related_model, item) else Utils.updateOrNew(item, @reverse_model_type)) for item in relateds) related_ids = (Utils.dataId(related) for related in relateds) collection.add(relateds) if model.isLoaded(@key) # check for needing load (model.setLoaded(@key, false); break) for related in relateds when not related.isLoaded() # patch in store if @join_table queue = new Queue(1) for related_id in related_ids do (related_id) => queue.defer (callback) => return callback(new Error "Many.patchAdd: cannot add an new model. Please save first.") unless related_id add = (callback) => attributes = {} attributes[@foreign_key] = model.id attributes[@reverse_relation.foreign_key] = related_id # console.log "Creating join for: #{@model_type.model_name} join: #{Utils.inspect(attributes)}" join = new @join_table(attributes) join.save callback # just create another entry return add(callback) if @reverse_relation.type is 'hasMany' # check for changes (query = {})[@reverse_relation.foreign_key] = related_id return @join_table.find query, (err, join_table_json) => return callback(err) if err return add(callback) unless join_table_json # create a new join table entry return callback() if join_table_json[@foreign_key] is model.id # already related # update existing relationship join_table_json[@foreign_key] = model.id Utils.modelJSONSave(join_table_json, @join_table, callback) queue.await callback else query = {id: $in: related_ids} @reverse_model_type.cursor(query).toJSON (err, related_jsons) => queue = new Queue(1) for related_json in related_jsons do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = model.id Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback patchRemove: (model, relateds, callback) -> return callback(new Error "Many.patchRemove: model has null id for: #{@key}") unless model.id # REMOVE ALL if arguments.length is 2 callback = relateds return callback() if not @reverse_relation if Utils.isModel(model) delete Utils.orSet(model, 'rel_dirty', {})[@key] collection = @_ensureCollection(model) related_models = _.clone(collection.models) else related_models = (new @reverse_model_type(json) for json in (model[@key] or [])) # clear in memory for related_model in related_models related_model.set(@foreign_key, null) cache.set(related_model.id, related_model) if cache = related_model.cache() # ensure the cache is up-to-date # clear in store through join table if @join_table (query = {})[@join_key] = model.id return @join_table.destroy(query, callback) # clear back links on models and save else (query = {})[@reverse_relation.foreign_key] = model.id @reverse_model_type.cursor(query).toJSON (err, json) => return callback(err) if err # clear reverses queue = new Queue(1) for related_json in json do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = null Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback return # REMOVE SOME return callback(new Error('Many.patchRemove: embedded relationships are not supported')) if @isEmbedded() return callback(new Error('One.patchRemove: missing model for remove')) unless relateds relateds = [relateds] unless _.isArray(relateds) collection = @_ensureCollection(model) # destroy in memory for related in relateds for current_related_model in collection.models (collection.remove(current_related_model); break) if Utils.dataIsSameModel(current_related_model, related) # a match related_ids = (Utils.dataId(related) for related in relateds) # clear in store through join table if @join_table # can directly destroy the join table entry query = {} query[@join_key] = model.id query[@reverse_relation.join_key] = {$in: related_ids} @join_table.destroy query, callback # clear back links on models and save else query = {} query[@reverse_relation.foreign_key] = model.id query.id = {$in: related_ids} @reverse_model_type.cursor(query).toJSON (err, json) => return callback(err) if err # clear reverses queue = new Queue(1) for related_json in json do (related_json) => queue.defer (callback) => related_json[@reverse_relation.foreign_key] = null Utils.modelJSONSave(related_json, @reverse_model_type, callback) queue.await callback cursor: (model, key, query) -> json = if Utils.isModel(model) then model.attributes else model (query = _.clone(query or {}))[if @join_table then @join_key else @reverse_relation.foreign_key] = json[@model_type::idAttribute] (query.$values or= []).push('id') if key is @virtual_id_accessor return @reverse_model_type.cursor(query) #################################### # Internal #################################### _bindBacklinks: (model) -> return collection if (collection = model.attributes[@key]) instanceof @collection_type collection = model.attributes[@key] = new @collection_type() return collection unless @reverse_relation # no back links events = Utils.set(collection, 'events', {}) events.add = (related_model) => if @reverse_relation.add @reverse_relation.add(related_model, model) else current_model = related_model.get(@reverse_relation.key) is_current = model.id and (Utils.dataId(current_model) is model.id) related_model.set(@reverse_relation.key, model) if not is_current or (is_current and not current_model.isLoaded()) events.remove = (related_model) => if @reverse_relation.remove @reverse_relation.remove(related_model, model) else current_model = related_model.get(@reverse_relation.key) related_model.set(@reverse_relation.key, null) if Utils.dataId(current_model) is model.id events.reset = (collection, options) => current_models = collection.models previous_models = options.previousModels or [] changes = _.groupBy(previous_models, (test) -> if !!_.find(current_models, (current_model) -> current_model.id is test.id) then 'kept' else 'removed') added = if changes.kept then _.select(current_models, (test) -> !_.find(changes.kept, (keep_model) -> keep_model.id is test.id)) else current_models # update back links (events.remove(related_model) for related_model in changes.removed) if changes.removed (events.add(related_model) for related_model in added) collection.on(method, events[method]) for method in ['add', 'remove', 'reset'] # bind return collection _unbindBacklinks: (model) -> return unless events = Utils.get(model, 'events') # already unbound Utils.unset(model, 'events') collection = model.attributes[@key] collection.models.splice() events = _.clone() for method in ['add', 'remove', 'reset'] # unbind collection.off(method, events[method]) events[method] = null return _ensureCollection: (model) -> return @_bindBacklinks(model) _hasChanged: (model) -> return !!Utils.orSet(model, 'rel_dirty', {})[@key] or model.hasChanged(@key) return false unless @reverse_relation collection = @_ensureCollection(model) return true for model in model.models when model.hasChanged(@reverse_relation.foreign_key) return false
[ { "context": " \"user\": {\n \"login\": \"test-user\"\n }\n },\n {\n ", "end": 998, "score": 0.9996069073677063, "start": 989, "tag": "USERNAME", "value": "test-user" }, { "context": " \"user\": {\n \"login\": \"test-user\"\n }\n }\n ])\n ", "end": 1169, "score": 0.9996454119682312, "start": 1160, "tag": "USERNAME", "value": "test-user" }, { "context": "(),\n \"html_url\": \"https://github.com/octocat/Hello-World/pulls/1\",\n \"title\": \"old", "end": 1429, "score": 0.9996958374977112, "start": 1422, "tag": "USERNAME", "value": "octocat" }, { "context": " \"user\": {\n \"login\": \"test-user\"\n },\n \"head\": {\n ", "end": 1644, "score": 0.9996469020843506, "start": 1635, "tag": "USERNAME", "value": "test-user" }, { "context": "(),\n \"html_url\": \"https://github.com/octocat/Hello-World/pulls/2\",\n \"title\": \"new", "end": 2088, "score": 0.9996254444122314, "start": 2081, "tag": "USERNAME", "value": "octocat" }, { "context": " \"user\": {\n \"login\": \"test-user\"\n },\n \"head\": {\n ", "end": 2303, "score": 0.9995309710502625, "start": 2294, "tag": "USERNAME", "value": "test-user" }, { "context": "(),\n \"html_url\": \"https://github.com/octocat/Hello-World/pulls/3\",\n \"title\": \"clo", "end": 2747, "score": 0.9996067881584167, "start": 2740, "tag": "USERNAME", "value": "octocat" }, { "context": " \"user\": {\n \"login\": \"test-user\"\n },\n \"head\": {\n ", "end": 2967, "score": 0.9995483756065369, "start": 2958, "tag": "USERNAME", "value": "test-user" }, { "context": "(),\n \"html_url\": \"https://github.com/octocat/Hello-World/pulls/4\",\n \"title\": \"clo", "end": 3415, "score": 0.9996192455291748, "start": 3408, "tag": "USERNAME", "value": "octocat" }, { "context": " \"user\": {\n \"login\": \"test-user\"\n },\n \"head\": {\n ", "end": 3635, "score": 0.9995792508125305, "start": 3626, "tag": "USERNAME", "value": "test-user" }, { "context": "torg/test-repo/statuses/testsha2?access_token=testtoken')\n .reply(200, [\n {\n ", "end": 4120, "score": 0.6945194602012634, "start": 4115, "tag": "KEY", "value": "token" }, { "context": "/testorg/test-repo/statuses/testsha3?access_token=testtoken')\n .reply(200, [\n {\n ", "end": 4298, "score": 0.757780909538269, "start": 4289, "tag": "KEY", "value": "testtoken" }, { "context": "ondorg/second-repo/statuses/testsha4?access_token=testtoken')\n .reply(200, [\n {\n ", "end": 4480, "score": 0.6663119792938232, "start": 4471, "tag": "KEY", "value": "testtoken" }, { "context": " object.url.should.equal \"https://github.com/octocat/Hello-World/pulls/2\"\n object.infos.shoul", "end": 4845, "score": 0.9995260238647461, "start": 4838, "tag": "USERNAME", "value": "octocat" }, { "context": " object.url.should.equal \"https://github.com/octocat/Hello-World/pulls/3\"\n object.infos.should.", "end": 5337, "score": 0.9995613694190979, "start": 5330, "tag": "USERNAME", "value": "octocat" }, { "context": "l true\n done()\n , 'https://github.com/testorg/test-repo/pull/3'\n\n it 'should be able to reso", "end": 5596, "score": 0.9731135368347168, "start": 5589, "tag": "USERNAME", "value": "testorg" }, { "context": " object.url.should.equal \"https://github.com/octocat/Hello-World/pulls/3\"\n object.infos.shoul", "end": 5914, "score": 0.9994513988494873, "start": 5907, "tag": "USERNAME", "value": "octocat" }, { "context": " object.url.should.equal \"https://github.com/octocat/Hello-World/pulls/4\"\n object.infos.shoul", "end": 6256, "score": 0.99945467710495, "start": 6249, "tag": "USERNAME", "value": "octocat" }, { "context": "n done()\n cb()\n , 'https://github.com/testorg/test-repo/pull/3', 'https://github.com/secondorg/", "end": 6556, "score": 0.9990278482437134, "start": 6549, "tag": "USERNAME", "value": "testorg" }, { "context": "om/testorg/test-repo/pull/3', 'https://github.com/secondorg/second-repo/pull/4'\n\n describe '#pulls()#isRepoI", "end": 6605, "score": 0.9961677193641663, "start": 6596, "tag": "USERNAME", "value": "secondorg" } ]
test/commands/pulls.coffee
boxuk/albot
0
Require = require('covershot').require.bind(null, require) should = require('chai').should() Commands = Require '../../lib/commands' Nock = Require 'nock' Moment = Require 'moment' describe 'Commands', () -> describe '#pulls()', () -> before () -> Nock('https://api.github.com') .persist() .get('/orgs/testorg/repos?page=1&per_page=100&access_token=testtoken') .reply(200, [ { "name": "test-repo", } ]) .get('/orgs/testorg/repos?page=2&per_page=100&access_token=testtoken') .reply(200, [ { "name": "test-repo", } ]) .get('/orgs/testorg/repos?page=3&per_page=100&access_token=testtoken') .reply(200, []) .get('/repos/testorg/test-repo/pulls?access_token=testtoken') .reply(200, [ { "number": 1, "title": "old-feature", "user": { "login": "test-user" } }, { "number": 2, "title": "new-feature", "user": { "login": "test-user" } } ]) .get('/repos/testorg/test-repo/pulls/1?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('years', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/1", "title": "old-feature", "mergeable": false, "state": "open", "comments": 50, "user": { "login": "test-user" }, "head": { "sha": "testsha1", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/pulls/2?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/2", "title": "new-feature", "mergeable": false, "state": "open", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha2", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/pulls/3?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/3", "title": "closed-feature", "mergeable": false, "state": "closed", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha3", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/secondorg/second-repo/pulls/4?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/4", "title": "closed-feature", "mergeable": false, "state": "closed", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha4", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/statuses/testsha1?access_token=testtoken') .reply(200, [ { "state": "success" } ]) .get('/repos/testorg/test-repo/statuses/testsha2?access_token=testtoken') .reply(200, [ { "state": "success" } ]) .get('/repos/testorg/test-repo/statuses/testsha3?access_token=testtoken') .reply(200, [ { "state": "success" } ]) .get('/repos/secondorg/second-repo/statuses/testsha4?access_token=testtoken') .reply(200, [ { "state": "failure" } ]) it 'should list Pull Requests sorted by creation date', (done) -> count = 0 Commands.pulls.action (object, cb) -> if (count is 0) object.title.should.equal "new-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/2" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *NEED REBASE*" object.status.should.equal true count += 1 if (count is 4) then done() cb() it 'should be able to resolve an URL', (done) -> Commands.pulls.action (object) -> object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/3" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal true done() , 'https://github.com/testorg/test-repo/pull/3' it 'should be able to resolve more than one URL', (done) -> count = 0 Commands.pulls.action (object, cb) -> count += 1 if (object.infos == "test-repo") object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/3" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal true else object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/4" object.infos.should.equal "second-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal false if count == 2 then done() cb() , 'https://github.com/testorg/test-repo/pull/3', 'https://github.com/secondorg/second-repo/pull/4' describe '#pulls()#isRepoInFilters()', () -> it 'should not accept unfilterd name', () -> test = Commands.pulls.isRepoInFilters("notinthelist") test.should.be.false it 'should accept any filter name', () -> test = Commands.pulls.isRepoInFilters("test-repo") test.should.be.true test = Commands.pulls.isRepoInFilters("another-one") test.should.be.true describe '#pulls()#shouldBeDisplayed()', () -> it 'should display normal request', () -> test = Commands.pulls.shouldBeDisplayed() test.should.be.true it '-without- criteria should hide requested term', () -> test = Commands.pulls.shouldBeDisplayed('without', 'stufF', 'Line with Stuff in it') test.should.be.false it '-without- criteria should display if term is not present', () -> test = Commands.pulls.shouldBeDisplayed('without', 'stuff', 'Line with things in it') test.should.be.true it '-with- criteria should display if term is present', () -> test = Commands.pulls.shouldBeDisplayed('with', 'stuff', 'Line with stuff') test.should.be.true it '-with- criteria should hide if term is not present', () -> test = Commands.pulls.shouldBeDisplayed('with', 'stuff', 'Line with things') test.should.be.false it '-recent- criteria should hide older than a week', () -> older = Moment().subtract('weeks', 3) test = Commands.pulls.shouldBeDisplayed('recent', undefined, 'Line with things', older) test.should.be.false it '-recent- criteria should show younger than a week', () -> younger = Moment().subtract('days', 1) test = Commands.pulls.shouldBeDisplayed('recent', undefined, 'Line with things', younger) test.should.be.true it '-recent- criteria should hide older than a month', () -> older = Moment().subtract('months', 5) test = Commands.pulls.shouldBeDisplayed('recent', 'months', 'Line with things', older) test.should.be.false it '-last- alongside a criteria should act like -with-', () -> test = Commands.pulls.shouldBeDisplayed('last', 'stuff', 'Line with stuff') test.should.be.true test = Commands.pulls.shouldBeDisplayed('last', 'stuff', 'Line with things') test.should.be.false it '-last- alone should display', () -> test = Commands.pulls.shouldBeDisplayed('last', undefined, 'Line with stuff') test.should.be.true it '-last- with a number should display', () -> test = Commands.pulls.shouldBeDisplayed('last', '5', 'Line with stuff') test.should.be.true it 'should display if criteria unknown', () -> test = Commands.pulls.shouldBeDisplayed('truc', 'stuff', 'Line with things in it') test.should.be.true it 'should display if term is null', () -> test = Commands.pulls.shouldBeDisplayed('without', undefined, 'Line with stuff') test.should.be.true describe '#pulls()#pickLastIfNeeded()', () -> list = ['stuff', 'things', 'truc', 'machin'] it 'should return the list if not -last-', () -> test = Commands.pulls.pickLastIfNeeded(undefined, undefined, list) test.should.be.list it '-last- should return the first one', () -> test = Commands.pulls.pickLastIfNeeded('last', undefined, list) test.should.have.length 1 test.should.include 'stuff' it '-last name- should return the first one', () -> test = Commands.pulls.pickLastIfNeeded('last', 'name', list) test.should.have.length 1 test.should.include 'stuff' it '-last 3- should return the first three', () -> test = Commands.pulls.pickLastIfNeeded('last', '3', list) test.should.have.length 3 test.should.include 'stuff' test.should.include 'things' test.should.include 'truc'
125375
Require = require('covershot').require.bind(null, require) should = require('chai').should() Commands = Require '../../lib/commands' Nock = Require 'nock' Moment = Require 'moment' describe 'Commands', () -> describe '#pulls()', () -> before () -> Nock('https://api.github.com') .persist() .get('/orgs/testorg/repos?page=1&per_page=100&access_token=testtoken') .reply(200, [ { "name": "test-repo", } ]) .get('/orgs/testorg/repos?page=2&per_page=100&access_token=testtoken') .reply(200, [ { "name": "test-repo", } ]) .get('/orgs/testorg/repos?page=3&per_page=100&access_token=testtoken') .reply(200, []) .get('/repos/testorg/test-repo/pulls?access_token=testtoken') .reply(200, [ { "number": 1, "title": "old-feature", "user": { "login": "test-user" } }, { "number": 2, "title": "new-feature", "user": { "login": "test-user" } } ]) .get('/repos/testorg/test-repo/pulls/1?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('years', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/1", "title": "old-feature", "mergeable": false, "state": "open", "comments": 50, "user": { "login": "test-user" }, "head": { "sha": "testsha1", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/pulls/2?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/2", "title": "new-feature", "mergeable": false, "state": "open", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha2", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/pulls/3?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/3", "title": "closed-feature", "mergeable": false, "state": "closed", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha3", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/secondorg/second-repo/pulls/4?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/4", "title": "closed-feature", "mergeable": false, "state": "closed", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha4", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/statuses/testsha1?access_token=testtoken') .reply(200, [ { "state": "success" } ]) .get('/repos/testorg/test-repo/statuses/testsha2?access_token=test<KEY>') .reply(200, [ { "state": "success" } ]) .get('/repos/testorg/test-repo/statuses/testsha3?access_token=<KEY>') .reply(200, [ { "state": "success" } ]) .get('/repos/secondorg/second-repo/statuses/testsha4?access_token=<KEY>') .reply(200, [ { "state": "failure" } ]) it 'should list Pull Requests sorted by creation date', (done) -> count = 0 Commands.pulls.action (object, cb) -> if (count is 0) object.title.should.equal "new-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/2" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *NEED REBASE*" object.status.should.equal true count += 1 if (count is 4) then done() cb() it 'should be able to resolve an URL', (done) -> Commands.pulls.action (object) -> object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/3" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal true done() , 'https://github.com/testorg/test-repo/pull/3' it 'should be able to resolve more than one URL', (done) -> count = 0 Commands.pulls.action (object, cb) -> count += 1 if (object.infos == "test-repo") object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/3" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal true else object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/4" object.infos.should.equal "second-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal false if count == 2 then done() cb() , 'https://github.com/testorg/test-repo/pull/3', 'https://github.com/secondorg/second-repo/pull/4' describe '#pulls()#isRepoInFilters()', () -> it 'should not accept unfilterd name', () -> test = Commands.pulls.isRepoInFilters("notinthelist") test.should.be.false it 'should accept any filter name', () -> test = Commands.pulls.isRepoInFilters("test-repo") test.should.be.true test = Commands.pulls.isRepoInFilters("another-one") test.should.be.true describe '#pulls()#shouldBeDisplayed()', () -> it 'should display normal request', () -> test = Commands.pulls.shouldBeDisplayed() test.should.be.true it '-without- criteria should hide requested term', () -> test = Commands.pulls.shouldBeDisplayed('without', 'stufF', 'Line with Stuff in it') test.should.be.false it '-without- criteria should display if term is not present', () -> test = Commands.pulls.shouldBeDisplayed('without', 'stuff', 'Line with things in it') test.should.be.true it '-with- criteria should display if term is present', () -> test = Commands.pulls.shouldBeDisplayed('with', 'stuff', 'Line with stuff') test.should.be.true it '-with- criteria should hide if term is not present', () -> test = Commands.pulls.shouldBeDisplayed('with', 'stuff', 'Line with things') test.should.be.false it '-recent- criteria should hide older than a week', () -> older = Moment().subtract('weeks', 3) test = Commands.pulls.shouldBeDisplayed('recent', undefined, 'Line with things', older) test.should.be.false it '-recent- criteria should show younger than a week', () -> younger = Moment().subtract('days', 1) test = Commands.pulls.shouldBeDisplayed('recent', undefined, 'Line with things', younger) test.should.be.true it '-recent- criteria should hide older than a month', () -> older = Moment().subtract('months', 5) test = Commands.pulls.shouldBeDisplayed('recent', 'months', 'Line with things', older) test.should.be.false it '-last- alongside a criteria should act like -with-', () -> test = Commands.pulls.shouldBeDisplayed('last', 'stuff', 'Line with stuff') test.should.be.true test = Commands.pulls.shouldBeDisplayed('last', 'stuff', 'Line with things') test.should.be.false it '-last- alone should display', () -> test = Commands.pulls.shouldBeDisplayed('last', undefined, 'Line with stuff') test.should.be.true it '-last- with a number should display', () -> test = Commands.pulls.shouldBeDisplayed('last', '5', 'Line with stuff') test.should.be.true it 'should display if criteria unknown', () -> test = Commands.pulls.shouldBeDisplayed('truc', 'stuff', 'Line with things in it') test.should.be.true it 'should display if term is null', () -> test = Commands.pulls.shouldBeDisplayed('without', undefined, 'Line with stuff') test.should.be.true describe '#pulls()#pickLastIfNeeded()', () -> list = ['stuff', 'things', 'truc', 'machin'] it 'should return the list if not -last-', () -> test = Commands.pulls.pickLastIfNeeded(undefined, undefined, list) test.should.be.list it '-last- should return the first one', () -> test = Commands.pulls.pickLastIfNeeded('last', undefined, list) test.should.have.length 1 test.should.include 'stuff' it '-last name- should return the first one', () -> test = Commands.pulls.pickLastIfNeeded('last', 'name', list) test.should.have.length 1 test.should.include 'stuff' it '-last 3- should return the first three', () -> test = Commands.pulls.pickLastIfNeeded('last', '3', list) test.should.have.length 3 test.should.include 'stuff' test.should.include 'things' test.should.include 'truc'
true
Require = require('covershot').require.bind(null, require) should = require('chai').should() Commands = Require '../../lib/commands' Nock = Require 'nock' Moment = Require 'moment' describe 'Commands', () -> describe '#pulls()', () -> before () -> Nock('https://api.github.com') .persist() .get('/orgs/testorg/repos?page=1&per_page=100&access_token=testtoken') .reply(200, [ { "name": "test-repo", } ]) .get('/orgs/testorg/repos?page=2&per_page=100&access_token=testtoken') .reply(200, [ { "name": "test-repo", } ]) .get('/orgs/testorg/repos?page=3&per_page=100&access_token=testtoken') .reply(200, []) .get('/repos/testorg/test-repo/pulls?access_token=testtoken') .reply(200, [ { "number": 1, "title": "old-feature", "user": { "login": "test-user" } }, { "number": 2, "title": "new-feature", "user": { "login": "test-user" } } ]) .get('/repos/testorg/test-repo/pulls/1?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('years', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/1", "title": "old-feature", "mergeable": false, "state": "open", "comments": 50, "user": { "login": "test-user" }, "head": { "sha": "testsha1", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/pulls/2?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/2", "title": "new-feature", "mergeable": false, "state": "open", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha2", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/pulls/3?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/3", "title": "closed-feature", "mergeable": false, "state": "closed", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha3", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/secondorg/second-repo/pulls/4?access_token=testtoken') .reply(200, { "created_at": Moment().subtract('months', 2).format(), "html_url": "https://github.com/octocat/Hello-World/pulls/4", "title": "closed-feature", "mergeable": false, "state": "closed", "comments": 10, "user": { "login": "test-user" }, "head": { "sha": "testsha4", "ref": "pr-branch" }, "base": { "ref": "master" } } ) .get('/repos/testorg/test-repo/statuses/testsha1?access_token=testtoken') .reply(200, [ { "state": "success" } ]) .get('/repos/testorg/test-repo/statuses/testsha2?access_token=testPI:KEY:<KEY>END_PI') .reply(200, [ { "state": "success" } ]) .get('/repos/testorg/test-repo/statuses/testsha3?access_token=PI:KEY:<KEY>END_PI') .reply(200, [ { "state": "success" } ]) .get('/repos/secondorg/second-repo/statuses/testsha4?access_token=PI:KEY:<KEY>END_PI') .reply(200, [ { "state": "failure" } ]) it 'should list Pull Requests sorted by creation date', (done) -> count = 0 Commands.pulls.action (object, cb) -> if (count is 0) object.title.should.equal "new-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/2" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *NEED REBASE*" object.status.should.equal true count += 1 if (count is 4) then done() cb() it 'should be able to resolve an URL', (done) -> Commands.pulls.action (object) -> object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/3" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal true done() , 'https://github.com/testorg/test-repo/pull/3' it 'should be able to resolve more than one URL', (done) -> count = 0 Commands.pulls.action (object, cb) -> count += 1 if (object.infos == "test-repo") object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/3" object.infos.should.equal "test-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal true else object.title.should.equal "closed-feature" object.url.should.equal "https://github.com/octocat/Hello-World/pulls/4" object.infos.should.equal "second-repo" object.comments.should.equal "(pr-branch -> master) - 2 months ago - 10 comments - *CLOSED*" object.status.should.equal false if count == 2 then done() cb() , 'https://github.com/testorg/test-repo/pull/3', 'https://github.com/secondorg/second-repo/pull/4' describe '#pulls()#isRepoInFilters()', () -> it 'should not accept unfilterd name', () -> test = Commands.pulls.isRepoInFilters("notinthelist") test.should.be.false it 'should accept any filter name', () -> test = Commands.pulls.isRepoInFilters("test-repo") test.should.be.true test = Commands.pulls.isRepoInFilters("another-one") test.should.be.true describe '#pulls()#shouldBeDisplayed()', () -> it 'should display normal request', () -> test = Commands.pulls.shouldBeDisplayed() test.should.be.true it '-without- criteria should hide requested term', () -> test = Commands.pulls.shouldBeDisplayed('without', 'stufF', 'Line with Stuff in it') test.should.be.false it '-without- criteria should display if term is not present', () -> test = Commands.pulls.shouldBeDisplayed('without', 'stuff', 'Line with things in it') test.should.be.true it '-with- criteria should display if term is present', () -> test = Commands.pulls.shouldBeDisplayed('with', 'stuff', 'Line with stuff') test.should.be.true it '-with- criteria should hide if term is not present', () -> test = Commands.pulls.shouldBeDisplayed('with', 'stuff', 'Line with things') test.should.be.false it '-recent- criteria should hide older than a week', () -> older = Moment().subtract('weeks', 3) test = Commands.pulls.shouldBeDisplayed('recent', undefined, 'Line with things', older) test.should.be.false it '-recent- criteria should show younger than a week', () -> younger = Moment().subtract('days', 1) test = Commands.pulls.shouldBeDisplayed('recent', undefined, 'Line with things', younger) test.should.be.true it '-recent- criteria should hide older than a month', () -> older = Moment().subtract('months', 5) test = Commands.pulls.shouldBeDisplayed('recent', 'months', 'Line with things', older) test.should.be.false it '-last- alongside a criteria should act like -with-', () -> test = Commands.pulls.shouldBeDisplayed('last', 'stuff', 'Line with stuff') test.should.be.true test = Commands.pulls.shouldBeDisplayed('last', 'stuff', 'Line with things') test.should.be.false it '-last- alone should display', () -> test = Commands.pulls.shouldBeDisplayed('last', undefined, 'Line with stuff') test.should.be.true it '-last- with a number should display', () -> test = Commands.pulls.shouldBeDisplayed('last', '5', 'Line with stuff') test.should.be.true it 'should display if criteria unknown', () -> test = Commands.pulls.shouldBeDisplayed('truc', 'stuff', 'Line with things in it') test.should.be.true it 'should display if term is null', () -> test = Commands.pulls.shouldBeDisplayed('without', undefined, 'Line with stuff') test.should.be.true describe '#pulls()#pickLastIfNeeded()', () -> list = ['stuff', 'things', 'truc', 'machin'] it 'should return the list if not -last-', () -> test = Commands.pulls.pickLastIfNeeded(undefined, undefined, list) test.should.be.list it '-last- should return the first one', () -> test = Commands.pulls.pickLastIfNeeded('last', undefined, list) test.should.have.length 1 test.should.include 'stuff' it '-last name- should return the first one', () -> test = Commands.pulls.pickLastIfNeeded('last', 'name', list) test.should.have.length 1 test.should.include 'stuff' it '-last 3- should return the first three', () -> test = Commands.pulls.pickLastIfNeeded('last', '3', list) test.should.have.length 3 test.should.include 'stuff' test.should.include 'things' test.should.include 'truc'
[ { "context": "rl\"\n suggestAddMembersCtrl.contactQuery = 'lololo@lolo.com'\n\n result = suggestAddMembersCtrl.isEmail(", "end": 1567, "score": 0.9998652338981628, "start": 1552, "tag": "EMAIL", "value": "lololo@lolo.com" }, { "context": " {\n full_name_display: 'Abel Sonofadan'\n username: 'abel'\n },\n", "end": 1877, "score": 0.9998723864555359, "start": 1863, "tag": "NAME", "value": "Abel Sonofadan" }, { "context": "play: 'Abel Sonofadan'\n username: 'abel'\n },\n {\n ful", "end": 1910, "score": 0.9994720220565796, "start": 1906, "tag": "USERNAME", "value": "abel" }, { "context": " {\n full_name_display: 'Cain Sonofadan'\n username: 'cain'\n }\n ", "end": 1991, "score": 0.9998547434806824, "start": 1977, "tag": "NAME", "value": "Cain Sonofadan" }, { "context": "play: 'Cain Sonofadan'\n username: 'cain'\n }\n ])\n\n suggestAddMemb", "end": 2024, "score": 0.9995793104171753, "start": 2020, "tag": "USERNAME", "value": "cain" }, { "context": "])\n\n suggestAddMembersCtrl.contactQuery = 'Cain Sonofadan'\n\n suggestAddMembersCtrl.filterContacts()\n", "end": 2112, "score": 0.9990946650505066, "start": 2098, "tag": "NAME", "value": "Cain Sonofadan" }, { "context": "oller \"SuggestAddMembersCtrl\"\n\n contact = 'contact'\n\n suggestAddMembersCtrl.onInviteSuggested", "end": 2360, "score": 0.9073748588562012, "start": 2353, "tag": "USERNAME", "value": "contact" } ]
app/modules/invite-members/suggest-add-members/suggest-add-members.controller.spec.coffee
threefoldtech/Threefold-Circles-front
0
### # Copyright (C) 2014-2018 Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: invite-members/suggest-add-members/suggest-add-members.controller.spec.coffee ### describe "SuggestAddMembersController", -> suggestAddMembersCtrl = null provide = null controller = null mocks = {} _mocks = () -> module ($provide) -> provide = $provide return null beforeEach -> module "taigaAdmin" _mocks() inject ($controller) -> controller = $controller it "is email - wrong", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contactQuery = 'lololo' result = suggestAddMembersCtrl.isEmail() expect(result).to.be.false it "is email - true", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contactQuery = 'lololo@lolo.com' result = suggestAddMembersCtrl.isEmail() expect(result).to.be.true it "filter contacts", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contacts = Immutable.fromJS([ { full_name_display: 'Abel Sonofadan' username: 'abel' }, { full_name_display: 'Cain Sonofadan' username: 'cain' } ]) suggestAddMembersCtrl.contactQuery = 'Cain Sonofadan' suggestAddMembersCtrl.filterContacts() expect(suggestAddMembersCtrl.filteredContacts.size).to.be.equal(1) it "set invited", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" contact = 'contact' suggestAddMembersCtrl.onInviteSuggested = sinon.stub() suggestAddMembersCtrl.setInvited(contact) expect(suggestAddMembersCtrl.onInviteSuggested).has.been.calledWith({'contact': contact})
25627
### # Copyright (C) 2014-2018 Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: invite-members/suggest-add-members/suggest-add-members.controller.spec.coffee ### describe "SuggestAddMembersController", -> suggestAddMembersCtrl = null provide = null controller = null mocks = {} _mocks = () -> module ($provide) -> provide = $provide return null beforeEach -> module "taigaAdmin" _mocks() inject ($controller) -> controller = $controller it "is email - wrong", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contactQuery = 'lololo' result = suggestAddMembersCtrl.isEmail() expect(result).to.be.false it "is email - true", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contactQuery = '<EMAIL>' result = suggestAddMembersCtrl.isEmail() expect(result).to.be.true it "filter contacts", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contacts = Immutable.fromJS([ { full_name_display: '<NAME>' username: 'abel' }, { full_name_display: '<NAME>' username: 'cain' } ]) suggestAddMembersCtrl.contactQuery = '<NAME>' suggestAddMembersCtrl.filterContacts() expect(suggestAddMembersCtrl.filteredContacts.size).to.be.equal(1) it "set invited", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" contact = 'contact' suggestAddMembersCtrl.onInviteSuggested = sinon.stub() suggestAddMembersCtrl.setInvited(contact) expect(suggestAddMembersCtrl.onInviteSuggested).has.been.calledWith({'contact': contact})
true
### # Copyright (C) 2014-2018 Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: invite-members/suggest-add-members/suggest-add-members.controller.spec.coffee ### describe "SuggestAddMembersController", -> suggestAddMembersCtrl = null provide = null controller = null mocks = {} _mocks = () -> module ($provide) -> provide = $provide return null beforeEach -> module "taigaAdmin" _mocks() inject ($controller) -> controller = $controller it "is email - wrong", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contactQuery = 'lololo' result = suggestAddMembersCtrl.isEmail() expect(result).to.be.false it "is email - true", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contactQuery = 'PI:EMAIL:<EMAIL>END_PI' result = suggestAddMembersCtrl.isEmail() expect(result).to.be.true it "filter contacts", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" suggestAddMembersCtrl.contacts = Immutable.fromJS([ { full_name_display: 'PI:NAME:<NAME>END_PI' username: 'abel' }, { full_name_display: 'PI:NAME:<NAME>END_PI' username: 'cain' } ]) suggestAddMembersCtrl.contactQuery = 'PI:NAME:<NAME>END_PI' suggestAddMembersCtrl.filterContacts() expect(suggestAddMembersCtrl.filteredContacts.size).to.be.equal(1) it "set invited", () -> suggestAddMembersCtrl = controller "SuggestAddMembersCtrl" contact = 'contact' suggestAddMembersCtrl.onInviteSuggested = sinon.stub() suggestAddMembersCtrl.setInvited(contact) expect(suggestAddMembersCtrl.onInviteSuggested).has.been.calledWith({'contact': contact})
[ { "context": "# name: watch.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈", "end": 32, "score": 0.9998965263366699, "start": 29, "tag": "NAME", "value": "沈维忠" }, { "context": "# name: watch.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizho", "end": 48, "score": 0.9998680949211121, "start": 35, "tag": "NAME", "value": "Shen Weizhong" }, { "context": "# name: watch.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Sta", "end": 61, "score": 0.9996166825294495, "start": 51, "tag": "NAME", "value": "Tony Stark" }, { "context": "维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )\n\n\n\n'use strict'\n\n\n", "end": 84, "score": 0.9995902180671692, "start": 81, "tag": "NAME", "value": "沈维忠" }, { "context": "hen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )\n\n\n\n'use strict'\n\n\n\ncfg = requir", "end": 100, "score": 0.9998602271080017, "start": 87, "tag": "NAME", "value": "Shen Weizhong" }, { "context": "ony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )\n\n\n\n'use strict'\n\n\n\ncfg = require '../config.", "end": 113, "score": 0.9994458556175232, "start": 103, "tag": "NAME", "value": "Tony Stark" } ]
dev/splited_tasks_for_gulp/watch.coffee
gitter-badger/is-object-brace
0
# name: watch.js # # author: 沈维忠 ( Shen Weizhong / Tony Stark ) # # Last Update: 沈维忠 ( Shen Weizhong / Tony Stark ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() gulp.task 'watch', -> gulp.watch '*.coffee', cwd: 'dev' , ['coffeescript'] return
198821
# name: watch.js # # author: <NAME> ( <NAME> / <NAME> ) # # Last Update: <NAME> ( <NAME> / <NAME> ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() gulp.task 'watch', -> gulp.watch '*.coffee', cwd: 'dev' , ['coffeescript'] return
true
# name: watch.js # # author: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) # # Last Update: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() gulp.task 'watch', -> gulp.watch '*.coffee', cwd: 'dev' , ['coffeescript'] return
[ { "context": "o ->\n url = \"https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json\"\n\n frame =", "end": 3945, "score": 0.9935333728790283, "start": 3937, "tag": "USERNAME", "value": "DealPete" }, { "context": "(\"title\", true)\n .text(\"35 fastest times up Alpe d'Huez and doping allegations\")\n \n \n ", "end": 14304, "score": 0.7342435121536255, "start": 14302, "tag": "NAME", "value": "Al" } ]
src/main.coffee
de-passage/data-visualization
0
d3 = Object.assign require("d3"), require("d3-time"), require("d3-scale") topojson = require "topojson" $ -> totalWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth totalHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight frameHeight = Math.max totalHeight * 0.8, 650 frameWidth = Math. max totalWidth * 0.9, 850 chartMargin = left: frameWidth * 0.08 right: frameWidth * 0.04 top: frameHeight * 0.1 bottom: frameHeight * 0.08 chartHeight = frameHeight - chartMargin.top - chartMargin.bottom chartWidth = frameWidth - chartMargin.left - chartMargin.right topMargin = Math.max(0, (totalHeight - frameHeight) / 2) tooltip = d3.select(document.body).append("div") .classed("tooltip transparent", true) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json" map_url = "https://d3js.org/world-50m.v1.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("width", frameWidth) .attr("height", frameHeight) projection = d3.geoEquirectangular() .scale(130) .rotate([0, 0]) .center([0, 0]) .translate([frameWidth / 2, frameHeight / 2]) geoPath = d3.geoPath() .projection(projection) d3.json map_url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the country data. See the logs for more details" return frame.append("g").selectAll("path") .data(topojson.feature(json, json.objects.countries).features) .enter() .append("path") .attr("fill", "#CCF") .attr("stroke", "#888") .attr("d", geoPath) d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the geo data. See the logs for more details" json.features.sort((a, b) -> b.properties.mass - a.properties.mass) massScale = d3.scalePow().exponent(0.5).domain([d3.min(json.features, (d) -> +d.properties.mass), d3.max(json.features, (d) -> +d.properties.mass)]).range([0.5, 20]) colorScale = d3.scaleLinear().domain([d3.min(json.features, (d) -> +(d.properties.id)), d3.max(json.features, (d) -> +(d.properties.id))]).range([0, 359]) f = (i) -> (d) -> projection([d.properties.reclong, d.properties.reclat])[i] frame.append("g").selectAll("circle") .data(json.features) .enter() .append("circle") .attr("cx",f(0)) .attr("cy",f(1)) .attr("r", (d) -> massScale +d.properties.mass) .style("fill", (d) -> "hsl(#{colorScale(+d.properties.id)}, 100%, 50%)" ) .style("stroke", "white") .style("fill-opacity", (d) -> massScale.range([0.8, 0.3]) d.properties.mass) .on("mouseover", (d, i) -> coords = d3.mouse document.body tooltip.html "Name: #{d.properties.name}<br> Year: #{(new Date d.properties.year).getFullYear()}<br> Mass: #{d.properties.mass}<br> Coordinates:<br>#{(+d.properties.reclat).toFixed(2)}, #{(+d.properties.reclong).toFixed(2)}<br> Class: #{d.properties.recclass}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) do -> url = "https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json" frame = d3.select("body") .append("div") .style("height", "#{frameHeight}px") .style("width", "#{frameWidth}px") .classed("chart", true) .append("div") .classed("abspos", true) .style("height", "#{frameHeight}px") .style("width", "#{frameWidth}px") .style("margin-top", topMargin) #context = frame.node().getContext("2d") d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the country data. See the logs for more details" return nodes = json.nodes links = json.links gravity = 0.03 simulation = d3.forceSimulation() .force("link", d3.forceLink().distance(30).strength(1)) .force("charge", d3.forceManyBody()) .force("x", d3.forceX(frameWidth / 2).strength(gravity)) .force("y", d3.forceY(frameHeight / 2).strength(gravity * 1.55)) .force("center", d3.forceCenter(frameWidth / 2, frameHeight / 2)) drawGraph = (n, l) -> l .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", (d) -> d.target.x) .attr("y2", (d) -> d.target.y) n .style("left", (d) -> (d.x - 8) + "px") .style("top", (d) -> (d.y - 5) + "px") link = frame.append("svg") .attr("width", frameWidth) .attr("height", frameHeight) .selectAll("line") .data(links) .enter().append("line") .style("stroke-width", (d) -> Math.sqrt d.value + "px") .style("stroke", "#CCC") lookupNeighbours = (idx) -> sourceLinks = (l.target.country for l in links when l.source.index == idx) targetLinks = (l.source.country for l in links when l.target.index == idx) sourceLinks.push target for target in targetLinks when sourceLinks.indexOf target == -1 sourceLinks.join(", ") node = frame .selectAll("img") .data(nodes) .enter().append("img") .attr("class", (d) -> "flag flag-#{d.code}") .on("mouseover", (d, i) -> coords = d3.mouse document.body tooltip.html "Country: #{d.country}<br><br>Neighbours: #{lookupNeighbours(i)}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) simulation .nodes(nodes) .on("tick", -> drawGraph(node, link)) simulation .force("link") .links(links) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/global-temperature.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("height", "#{frameHeight}") .attr("width", "#{frameWidth}") .style("margin-top", topMargin) chart = frame.append("g") .attr("transform", "translate(#{chartMargin.left}, #{chartMargin.top})") d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the heat map data. See the logs for more details" return data = json.monthlyVariance colors = ["darkblue", "blue", "yellow", "orange", "red", "darkred"] months = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."] minYear = d3.min(data, (d) -> d.year) maxYear = d3.max(data, (d) -> d.year) totalYears = maxYear - minYear monthsDomain = [d3.min(data, (d) -> d.month), d3.max(data, (d) -> d.month)] barWidth = chartWidth / totalYears barHeight = chartHeight / 12 xScale = d3.scaleLinear().range([0, chartWidth - barWidth]).domain([minYear, maxYear]) yScale = d3.scaleLinear().range([0, chartHeight - barHeight]).domain(monthsDomain) colorScale = d3.scaleQuantile().range(colors).domain([d3.min(data, (d) -> d.variance), d3.max(data, (d) -> d.variance)]) chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", (d) -> "translate(#{xScale d.year},#{yScale d.month})") .append("rect") .attr("width", barWidth) .attr("height", barHeight) .style("fill", (d) -> colorScale d.variance) .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "#{months[d.month - 1]} #{d.year}<br>Variance: #{d.variance}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) yAxis = d3.axisLeft().scale(yScale).tickFormat((d) -> months[d - 1]) xAxis = d3.axisBottom().scale(xScale) chart.append("g") .attr("transform", "translate(0, #{chartHeight})") .call(xAxis) .append("text") .classed("legend", true) .text("Year") .attr("x", "#{chartWidth/2}px") .attr("y", "#{chartMargin.bottom * 0.8}px") .style("text-anchor", "middle") chart.append("g") .attr("transform","translate(0,0)") .call(yAxis) .append("text") .text("Month") .classed("legend", true) .attr("x", "-#{chartHeight/2}px") .attr("y", "-55px") .attr("dy", ".35em") .style("text-anchor", "middle") .attr("transform", "rotate(-90)") frame.append("text") .attr("x", "20px") .attr("text-anchor", "start") .attr("y", "#{chartMargin.top * 0.6}px") .classed("title", true) .text("Heat map") frame.append("text") .attr("x", frameWidth - 10) .attr("text-anchor", "end") .attr("y", "#{chartMargin.top * 0.3}px") .text("Variance from global average (#{json.baseTemperature})") legendSize = 25 frame.append("g") .attr("transform", "translate(#{frameWidth - 100 - (colors.length*legendSize)},#{chartMargin.top * 0.5})") .selectAll("rect") .data(colors) .enter() .append("rect") .attr("transform", (d, i) -> "translate(#{i * legendSize}, 0)") .attr("width", legendSize) .attr("height", legendSize) .style("fill", (d) -> d) .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "Inteval: [#{colorScale.invertExtent(d)[0].toFixed(1)}, #{colorScale.invertExtent(d)[1].toFixed(1)}]" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/cyclist-data.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("height", "#{frameHeight}px") .attr("width", "#{frameWidth}px") .style("margin-top", topMargin) chart = frame.append("g") .attr("transform", "translate(#{chartMargin.left},#{chartMargin.top})") xAxis = d3.scaleLinear().range([0, chartWidth]) yAxis = d3.scaleTime().range([0, chartHeight]) timeParser = d3.timeParse("%M:%S") $.getJSON url, (data) -> xAxis.domain([d3.min(data, (d) -> d.Place) - 1, d3.max(data, (d) -> d.Place)]) shortestTime = new Date d3.min(data, (d) -> timeParser d.Time).getTime() - 15000 longestTime = d3.max(data, (d) -> timeParser d.Time) yAxis.domain([longestTime, shortestTime]) chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", (d, i) -> "translate(#{xAxis(d.Place)}, #{yAxis timeParser d.Time})") .append("circle") .attr("r", "5") .style("fill", (d) -> if d.Doping != "" then "red" else "steelblue") .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "Name: #{d.Name}<br>Nationality: #{d.Nationality}<br>Year: #{d.Year}<br>Time: #{d.Time}<br>Time Ranking: #{d.Place}#{if d.Doping != "" then "<br><br>" + d.Doping else ""}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) xAxisRender = d3.axisBottom().scale(xAxis).tickFormat((d) -> if d then d else "") yAxisRender = d3.axisLeft().scale(yAxis).ticks(d3.timeSecond, 15).tickFormat(d3.timeFormat("%M:%S")) chart.append("g") .attr("transform", "translate(0, #{chartHeight})") .call(xAxisRender) .append("text") .classed("legend", true) .text("Time ranking") .attr("x", "#{chartWidth/2}px") .attr("y", "#{chartMargin.bottom * 0.8}px") .style("text-anchor", "middle") chart.append("g") .attr("transform","translate(0,0)") .call(yAxisRender) .append("text") .text("Time") .classed("legend", true) .attr("x", "-#{chartHeight/2}px") .attr("y", "-55px") .attr("dy", ".35em") .style("text-anchor", "middle") .attr("transform", "rotate(-90)") frame.append("text") .attr("x", "#{frameWidth / 2}px") .attr("text-anchor", "middle") .attr("y", "#{chartMargin.top / 2}px") .classed("title", true) .text("35 fastest times up Alpe d'Huez and doping allegations")
151132
d3 = Object.assign require("d3"), require("d3-time"), require("d3-scale") topojson = require "topojson" $ -> totalWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth totalHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight frameHeight = Math.max totalHeight * 0.8, 650 frameWidth = Math. max totalWidth * 0.9, 850 chartMargin = left: frameWidth * 0.08 right: frameWidth * 0.04 top: frameHeight * 0.1 bottom: frameHeight * 0.08 chartHeight = frameHeight - chartMargin.top - chartMargin.bottom chartWidth = frameWidth - chartMargin.left - chartMargin.right topMargin = Math.max(0, (totalHeight - frameHeight) / 2) tooltip = d3.select(document.body).append("div") .classed("tooltip transparent", true) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json" map_url = "https://d3js.org/world-50m.v1.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("width", frameWidth) .attr("height", frameHeight) projection = d3.geoEquirectangular() .scale(130) .rotate([0, 0]) .center([0, 0]) .translate([frameWidth / 2, frameHeight / 2]) geoPath = d3.geoPath() .projection(projection) d3.json map_url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the country data. See the logs for more details" return frame.append("g").selectAll("path") .data(topojson.feature(json, json.objects.countries).features) .enter() .append("path") .attr("fill", "#CCF") .attr("stroke", "#888") .attr("d", geoPath) d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the geo data. See the logs for more details" json.features.sort((a, b) -> b.properties.mass - a.properties.mass) massScale = d3.scalePow().exponent(0.5).domain([d3.min(json.features, (d) -> +d.properties.mass), d3.max(json.features, (d) -> +d.properties.mass)]).range([0.5, 20]) colorScale = d3.scaleLinear().domain([d3.min(json.features, (d) -> +(d.properties.id)), d3.max(json.features, (d) -> +(d.properties.id))]).range([0, 359]) f = (i) -> (d) -> projection([d.properties.reclong, d.properties.reclat])[i] frame.append("g").selectAll("circle") .data(json.features) .enter() .append("circle") .attr("cx",f(0)) .attr("cy",f(1)) .attr("r", (d) -> massScale +d.properties.mass) .style("fill", (d) -> "hsl(#{colorScale(+d.properties.id)}, 100%, 50%)" ) .style("stroke", "white") .style("fill-opacity", (d) -> massScale.range([0.8, 0.3]) d.properties.mass) .on("mouseover", (d, i) -> coords = d3.mouse document.body tooltip.html "Name: #{d.properties.name}<br> Year: #{(new Date d.properties.year).getFullYear()}<br> Mass: #{d.properties.mass}<br> Coordinates:<br>#{(+d.properties.reclat).toFixed(2)}, #{(+d.properties.reclong).toFixed(2)}<br> Class: #{d.properties.recclass}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) do -> url = "https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json" frame = d3.select("body") .append("div") .style("height", "#{frameHeight}px") .style("width", "#{frameWidth}px") .classed("chart", true) .append("div") .classed("abspos", true) .style("height", "#{frameHeight}px") .style("width", "#{frameWidth}px") .style("margin-top", topMargin) #context = frame.node().getContext("2d") d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the country data. See the logs for more details" return nodes = json.nodes links = json.links gravity = 0.03 simulation = d3.forceSimulation() .force("link", d3.forceLink().distance(30).strength(1)) .force("charge", d3.forceManyBody()) .force("x", d3.forceX(frameWidth / 2).strength(gravity)) .force("y", d3.forceY(frameHeight / 2).strength(gravity * 1.55)) .force("center", d3.forceCenter(frameWidth / 2, frameHeight / 2)) drawGraph = (n, l) -> l .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", (d) -> d.target.x) .attr("y2", (d) -> d.target.y) n .style("left", (d) -> (d.x - 8) + "px") .style("top", (d) -> (d.y - 5) + "px") link = frame.append("svg") .attr("width", frameWidth) .attr("height", frameHeight) .selectAll("line") .data(links) .enter().append("line") .style("stroke-width", (d) -> Math.sqrt d.value + "px") .style("stroke", "#CCC") lookupNeighbours = (idx) -> sourceLinks = (l.target.country for l in links when l.source.index == idx) targetLinks = (l.source.country for l in links when l.target.index == idx) sourceLinks.push target for target in targetLinks when sourceLinks.indexOf target == -1 sourceLinks.join(", ") node = frame .selectAll("img") .data(nodes) .enter().append("img") .attr("class", (d) -> "flag flag-#{d.code}") .on("mouseover", (d, i) -> coords = d3.mouse document.body tooltip.html "Country: #{d.country}<br><br>Neighbours: #{lookupNeighbours(i)}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) simulation .nodes(nodes) .on("tick", -> drawGraph(node, link)) simulation .force("link") .links(links) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/global-temperature.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("height", "#{frameHeight}") .attr("width", "#{frameWidth}") .style("margin-top", topMargin) chart = frame.append("g") .attr("transform", "translate(#{chartMargin.left}, #{chartMargin.top})") d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the heat map data. See the logs for more details" return data = json.monthlyVariance colors = ["darkblue", "blue", "yellow", "orange", "red", "darkred"] months = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."] minYear = d3.min(data, (d) -> d.year) maxYear = d3.max(data, (d) -> d.year) totalYears = maxYear - minYear monthsDomain = [d3.min(data, (d) -> d.month), d3.max(data, (d) -> d.month)] barWidth = chartWidth / totalYears barHeight = chartHeight / 12 xScale = d3.scaleLinear().range([0, chartWidth - barWidth]).domain([minYear, maxYear]) yScale = d3.scaleLinear().range([0, chartHeight - barHeight]).domain(monthsDomain) colorScale = d3.scaleQuantile().range(colors).domain([d3.min(data, (d) -> d.variance), d3.max(data, (d) -> d.variance)]) chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", (d) -> "translate(#{xScale d.year},#{yScale d.month})") .append("rect") .attr("width", barWidth) .attr("height", barHeight) .style("fill", (d) -> colorScale d.variance) .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "#{months[d.month - 1]} #{d.year}<br>Variance: #{d.variance}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) yAxis = d3.axisLeft().scale(yScale).tickFormat((d) -> months[d - 1]) xAxis = d3.axisBottom().scale(xScale) chart.append("g") .attr("transform", "translate(0, #{chartHeight})") .call(xAxis) .append("text") .classed("legend", true) .text("Year") .attr("x", "#{chartWidth/2}px") .attr("y", "#{chartMargin.bottom * 0.8}px") .style("text-anchor", "middle") chart.append("g") .attr("transform","translate(0,0)") .call(yAxis) .append("text") .text("Month") .classed("legend", true) .attr("x", "-#{chartHeight/2}px") .attr("y", "-55px") .attr("dy", ".35em") .style("text-anchor", "middle") .attr("transform", "rotate(-90)") frame.append("text") .attr("x", "20px") .attr("text-anchor", "start") .attr("y", "#{chartMargin.top * 0.6}px") .classed("title", true) .text("Heat map") frame.append("text") .attr("x", frameWidth - 10) .attr("text-anchor", "end") .attr("y", "#{chartMargin.top * 0.3}px") .text("Variance from global average (#{json.baseTemperature})") legendSize = 25 frame.append("g") .attr("transform", "translate(#{frameWidth - 100 - (colors.length*legendSize)},#{chartMargin.top * 0.5})") .selectAll("rect") .data(colors) .enter() .append("rect") .attr("transform", (d, i) -> "translate(#{i * legendSize}, 0)") .attr("width", legendSize) .attr("height", legendSize) .style("fill", (d) -> d) .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "Inteval: [#{colorScale.invertExtent(d)[0].toFixed(1)}, #{colorScale.invertExtent(d)[1].toFixed(1)}]" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/cyclist-data.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("height", "#{frameHeight}px") .attr("width", "#{frameWidth}px") .style("margin-top", topMargin) chart = frame.append("g") .attr("transform", "translate(#{chartMargin.left},#{chartMargin.top})") xAxis = d3.scaleLinear().range([0, chartWidth]) yAxis = d3.scaleTime().range([0, chartHeight]) timeParser = d3.timeParse("%M:%S") $.getJSON url, (data) -> xAxis.domain([d3.min(data, (d) -> d.Place) - 1, d3.max(data, (d) -> d.Place)]) shortestTime = new Date d3.min(data, (d) -> timeParser d.Time).getTime() - 15000 longestTime = d3.max(data, (d) -> timeParser d.Time) yAxis.domain([longestTime, shortestTime]) chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", (d, i) -> "translate(#{xAxis(d.Place)}, #{yAxis timeParser d.Time})") .append("circle") .attr("r", "5") .style("fill", (d) -> if d.Doping != "" then "red" else "steelblue") .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "Name: #{d.Name}<br>Nationality: #{d.Nationality}<br>Year: #{d.Year}<br>Time: #{d.Time}<br>Time Ranking: #{d.Place}#{if d.Doping != "" then "<br><br>" + d.Doping else ""}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) xAxisRender = d3.axisBottom().scale(xAxis).tickFormat((d) -> if d then d else "") yAxisRender = d3.axisLeft().scale(yAxis).ticks(d3.timeSecond, 15).tickFormat(d3.timeFormat("%M:%S")) chart.append("g") .attr("transform", "translate(0, #{chartHeight})") .call(xAxisRender) .append("text") .classed("legend", true) .text("Time ranking") .attr("x", "#{chartWidth/2}px") .attr("y", "#{chartMargin.bottom * 0.8}px") .style("text-anchor", "middle") chart.append("g") .attr("transform","translate(0,0)") .call(yAxisRender) .append("text") .text("Time") .classed("legend", true) .attr("x", "-#{chartHeight/2}px") .attr("y", "-55px") .attr("dy", ".35em") .style("text-anchor", "middle") .attr("transform", "rotate(-90)") frame.append("text") .attr("x", "#{frameWidth / 2}px") .attr("text-anchor", "middle") .attr("y", "#{chartMargin.top / 2}px") .classed("title", true) .text("35 fastest times up <NAME>pe d'Huez and doping allegations")
true
d3 = Object.assign require("d3"), require("d3-time"), require("d3-scale") topojson = require "topojson" $ -> totalWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth totalHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight frameHeight = Math.max totalHeight * 0.8, 650 frameWidth = Math. max totalWidth * 0.9, 850 chartMargin = left: frameWidth * 0.08 right: frameWidth * 0.04 top: frameHeight * 0.1 bottom: frameHeight * 0.08 chartHeight = frameHeight - chartMargin.top - chartMargin.bottom chartWidth = frameWidth - chartMargin.left - chartMargin.right topMargin = Math.max(0, (totalHeight - frameHeight) / 2) tooltip = d3.select(document.body).append("div") .classed("tooltip transparent", true) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json" map_url = "https://d3js.org/world-50m.v1.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("width", frameWidth) .attr("height", frameHeight) projection = d3.geoEquirectangular() .scale(130) .rotate([0, 0]) .center([0, 0]) .translate([frameWidth / 2, frameHeight / 2]) geoPath = d3.geoPath() .projection(projection) d3.json map_url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the country data. See the logs for more details" return frame.append("g").selectAll("path") .data(topojson.feature(json, json.objects.countries).features) .enter() .append("path") .attr("fill", "#CCF") .attr("stroke", "#888") .attr("d", geoPath) d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the geo data. See the logs for more details" json.features.sort((a, b) -> b.properties.mass - a.properties.mass) massScale = d3.scalePow().exponent(0.5).domain([d3.min(json.features, (d) -> +d.properties.mass), d3.max(json.features, (d) -> +d.properties.mass)]).range([0.5, 20]) colorScale = d3.scaleLinear().domain([d3.min(json.features, (d) -> +(d.properties.id)), d3.max(json.features, (d) -> +(d.properties.id))]).range([0, 359]) f = (i) -> (d) -> projection([d.properties.reclong, d.properties.reclat])[i] frame.append("g").selectAll("circle") .data(json.features) .enter() .append("circle") .attr("cx",f(0)) .attr("cy",f(1)) .attr("r", (d) -> massScale +d.properties.mass) .style("fill", (d) -> "hsl(#{colorScale(+d.properties.id)}, 100%, 50%)" ) .style("stroke", "white") .style("fill-opacity", (d) -> massScale.range([0.8, 0.3]) d.properties.mass) .on("mouseover", (d, i) -> coords = d3.mouse document.body tooltip.html "Name: #{d.properties.name}<br> Year: #{(new Date d.properties.year).getFullYear()}<br> Mass: #{d.properties.mass}<br> Coordinates:<br>#{(+d.properties.reclat).toFixed(2)}, #{(+d.properties.reclong).toFixed(2)}<br> Class: #{d.properties.recclass}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) do -> url = "https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json" frame = d3.select("body") .append("div") .style("height", "#{frameHeight}px") .style("width", "#{frameWidth}px") .classed("chart", true) .append("div") .classed("abspos", true) .style("height", "#{frameHeight}px") .style("width", "#{frameWidth}px") .style("margin-top", topMargin) #context = frame.node().getContext("2d") d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the country data. See the logs for more details" return nodes = json.nodes links = json.links gravity = 0.03 simulation = d3.forceSimulation() .force("link", d3.forceLink().distance(30).strength(1)) .force("charge", d3.forceManyBody()) .force("x", d3.forceX(frameWidth / 2).strength(gravity)) .force("y", d3.forceY(frameHeight / 2).strength(gravity * 1.55)) .force("center", d3.forceCenter(frameWidth / 2, frameHeight / 2)) drawGraph = (n, l) -> l .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", (d) -> d.target.x) .attr("y2", (d) -> d.target.y) n .style("left", (d) -> (d.x - 8) + "px") .style("top", (d) -> (d.y - 5) + "px") link = frame.append("svg") .attr("width", frameWidth) .attr("height", frameHeight) .selectAll("line") .data(links) .enter().append("line") .style("stroke-width", (d) -> Math.sqrt d.value + "px") .style("stroke", "#CCC") lookupNeighbours = (idx) -> sourceLinks = (l.target.country for l in links when l.source.index == idx) targetLinks = (l.source.country for l in links when l.target.index == idx) sourceLinks.push target for target in targetLinks when sourceLinks.indexOf target == -1 sourceLinks.join(", ") node = frame .selectAll("img") .data(nodes) .enter().append("img") .attr("class", (d) -> "flag flag-#{d.code}") .on("mouseover", (d, i) -> coords = d3.mouse document.body tooltip.html "Country: #{d.country}<br><br>Neighbours: #{lookupNeighbours(i)}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) simulation .nodes(nodes) .on("tick", -> drawGraph(node, link)) simulation .force("link") .links(links) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/global-temperature.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("height", "#{frameHeight}") .attr("width", "#{frameWidth}") .style("margin-top", topMargin) chart = frame.append("g") .attr("transform", "translate(#{chartMargin.left}, #{chartMargin.top})") d3.json url, (error, json) -> if error? console.log "Error: ", JSON.stringify error alert "An error has occured while loading the heat map data. See the logs for more details" return data = json.monthlyVariance colors = ["darkblue", "blue", "yellow", "orange", "red", "darkred"] months = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."] minYear = d3.min(data, (d) -> d.year) maxYear = d3.max(data, (d) -> d.year) totalYears = maxYear - minYear monthsDomain = [d3.min(data, (d) -> d.month), d3.max(data, (d) -> d.month)] barWidth = chartWidth / totalYears barHeight = chartHeight / 12 xScale = d3.scaleLinear().range([0, chartWidth - barWidth]).domain([minYear, maxYear]) yScale = d3.scaleLinear().range([0, chartHeight - barHeight]).domain(monthsDomain) colorScale = d3.scaleQuantile().range(colors).domain([d3.min(data, (d) -> d.variance), d3.max(data, (d) -> d.variance)]) chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", (d) -> "translate(#{xScale d.year},#{yScale d.month})") .append("rect") .attr("width", barWidth) .attr("height", barHeight) .style("fill", (d) -> colorScale d.variance) .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "#{months[d.month - 1]} #{d.year}<br>Variance: #{d.variance}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) yAxis = d3.axisLeft().scale(yScale).tickFormat((d) -> months[d - 1]) xAxis = d3.axisBottom().scale(xScale) chart.append("g") .attr("transform", "translate(0, #{chartHeight})") .call(xAxis) .append("text") .classed("legend", true) .text("Year") .attr("x", "#{chartWidth/2}px") .attr("y", "#{chartMargin.bottom * 0.8}px") .style("text-anchor", "middle") chart.append("g") .attr("transform","translate(0,0)") .call(yAxis) .append("text") .text("Month") .classed("legend", true) .attr("x", "-#{chartHeight/2}px") .attr("y", "-55px") .attr("dy", ".35em") .style("text-anchor", "middle") .attr("transform", "rotate(-90)") frame.append("text") .attr("x", "20px") .attr("text-anchor", "start") .attr("y", "#{chartMargin.top * 0.6}px") .classed("title", true) .text("Heat map") frame.append("text") .attr("x", frameWidth - 10) .attr("text-anchor", "end") .attr("y", "#{chartMargin.top * 0.3}px") .text("Variance from global average (#{json.baseTemperature})") legendSize = 25 frame.append("g") .attr("transform", "translate(#{frameWidth - 100 - (colors.length*legendSize)},#{chartMargin.top * 0.5})") .selectAll("rect") .data(colors) .enter() .append("rect") .attr("transform", (d, i) -> "translate(#{i * legendSize}, 0)") .attr("width", legendSize) .attr("height", legendSize) .style("fill", (d) -> d) .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "Inteval: [#{colorScale.invertExtent(d)[0].toFixed(1)}, #{colorScale.invertExtent(d)[1].toFixed(1)}]" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) do -> url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/cyclist-data.json" frame = d3.select("body") .append("svg") .classed("chart", true) .attr("height", "#{frameHeight}px") .attr("width", "#{frameWidth}px") .style("margin-top", topMargin) chart = frame.append("g") .attr("transform", "translate(#{chartMargin.left},#{chartMargin.top})") xAxis = d3.scaleLinear().range([0, chartWidth]) yAxis = d3.scaleTime().range([0, chartHeight]) timeParser = d3.timeParse("%M:%S") $.getJSON url, (data) -> xAxis.domain([d3.min(data, (d) -> d.Place) - 1, d3.max(data, (d) -> d.Place)]) shortestTime = new Date d3.min(data, (d) -> timeParser d.Time).getTime() - 15000 longestTime = d3.max(data, (d) -> timeParser d.Time) yAxis.domain([longestTime, shortestTime]) chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", (d, i) -> "translate(#{xAxis(d.Place)}, #{yAxis timeParser d.Time})") .append("circle") .attr("r", "5") .style("fill", (d) -> if d.Doping != "" then "red" else "steelblue") .on("mouseover", (d) -> coords = d3.mouse document.body tooltip.html "Name: #{d.Name}<br>Nationality: #{d.Nationality}<br>Year: #{d.Year}<br>Time: #{d.Time}<br>Time Ranking: #{d.Place}#{if d.Doping != "" then "<br><br>" + d.Doping else ""}" tooltip.classed "transparent", false tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px") ) .on("mousemove", -> coords = d3.mouse document.body tooltip.style("left", "#{coords[0] + 20}px").style("top", "#{coords[1] + topMargin}px")) .on("mouseout", -> tooltip.classed "transparent", true) xAxisRender = d3.axisBottom().scale(xAxis).tickFormat((d) -> if d then d else "") yAxisRender = d3.axisLeft().scale(yAxis).ticks(d3.timeSecond, 15).tickFormat(d3.timeFormat("%M:%S")) chart.append("g") .attr("transform", "translate(0, #{chartHeight})") .call(xAxisRender) .append("text") .classed("legend", true) .text("Time ranking") .attr("x", "#{chartWidth/2}px") .attr("y", "#{chartMargin.bottom * 0.8}px") .style("text-anchor", "middle") chart.append("g") .attr("transform","translate(0,0)") .call(yAxisRender) .append("text") .text("Time") .classed("legend", true) .attr("x", "-#{chartHeight/2}px") .attr("y", "-55px") .attr("dy", ".35em") .style("text-anchor", "middle") .attr("transform", "rotate(-90)") frame.append("text") .attr("x", "#{frameWidth / 2}px") .attr("text-anchor", "middle") .attr("y", "#{chartMargin.top / 2}px") .classed("title", true) .text("35 fastest times up PI:NAME:<NAME>END_PIpe d'Huez and doping allegations")
[ { "context": "r templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ\n\n\ttemplateData:\n\n\t\t# Specify some", "end": 1527, "score": 0.9426062703132629, "start": 1522, "tag": "USERNAME", "value": "bevry" }, { "context": "\t\t\"\"\"\n\n\t\t\t# The website author's name\n\t\t\tauthor: \"JOONGSEOB VITO KIM\"\n\n\t\t\t# The website author's email\n\t\t\temail: \"dora", "end": 2265, "score": 0.9998093843460083, "start": 2247, "tag": "NAME", "value": "JOONGSEOB VITO KIM" }, { "context": " KIM\"\n\n\t\t\t# The website author's email\n\t\t\temail: \"dorajissanai@nate.com\"\n\n\t\t\t# Styles\n\t\t\tstyles: [\n\t\t\t\t\"http://yui.yahooa", "end": 2332, "score": 0.9999321699142456, "start": 2311, "tag": "EMAIL", "value": "dorajissanai@nate.com" } ]
docpad.coffee
dorajistyle/blogger-docpad
0
cheerio = require('cheerio') url = require('url') categories = { '여행': ['준비'], '대한민국': ['서울','인천','부산','경기도','강원도','충청남도','충청북도','전라남도','전라북도','경상남도','경상북도','제주도'], # '대한민국': ['서울','인천','대전','대구','울산','광주','부산','경기도','강원도','충청남도','충청북도','전라남도','전라북도','경상남도','경상북도','제주도'], '유럽': ['이탈리아','스페인','프랑스','독일','영국','아일랜드','노르웨이','스웨덴','오스트리아','헝가리','슬로바키아'], '아시아': ['중국','일본','태국','라오스','베트남','말레이시아','필리핀'], '중동': ['터키','시리아','요르단'], '아프리카': ['이집트'], '북미': ['미국','캐나다'], '남미': [], '오세아니아': [], '책': ['수필','소설','희곡','시','철학','건강비결','사회','창작기술','자기계발','기술','기타_책'], '지식': ['언어','인문학','기타_지식'], '건강': ['식사','운동','명상','기타_건강'], '영화': ['한국영화','영국영화','미국영화','프랑스영화','이탈리아영화','스웨덴영화','독일영화','루마니아영화','홍콩영화','인도영화'], '드라마': ['국내','국외'], '음악': ['재즈','록','힙합','팝','어쿠스틱','트랜스','기타_음악'], '문화': ['연극','뮤지컬','음악회','춤','전시','콘퍼런스'], '조리법': ['요리','활동식','음료'], '사용기': ['전자제품', '음향', '기타_사용기'], '동물': ['고양이'], 'IT': ['web','db','sccm','testing','blog', 'OS','3D','development','mobile','환경','이론','tip','app','etc'], '취미': ['사진', '자전거','무술','수영','다이빙', '음주가무'], '월풍': ['독백','일기','사유','창작','삶'] } # The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON docpadConfig = { #envirnments: # static: # plugins: # cleanurls: # static: true # trailingSlashes: false # ================================= # Template Data # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: # Specify some site properties site: # The production url of our website url: "http://dorajistyle.net" # Here are some old site urls that you would like to redirect from oldUrls: [ 'http://dorajistyle.net' ] # The default title of our website title: "월풍도원(月風道院) STATIC Version - Delight on the Simple Life" # The website description (for SEO) description: """ 방랑자의 이야기 STATIC 버전.(STATIC version of stories about vagabond.) """ # The website keywords (for SEO) separated by commas keywords: """ 여행,명상,철학,방랑,행복,인생,IT,vagabond,travel,trip,meditation,philosophy,happiness,life """ # The website author's name author: "JOONGSEOB VITO KIM" # The website author's email email: "dorajissanai@nate.com" # Styles styles: [ "http://yui.yahooapis.com/pure/0.3.0/pure-min.css" "http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" "/styles/style.css" ] # Scripts scripts: [ "/scripts/main.js" ] # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description getPageUrlWithHostname: -> "#{@site.url}#{@document.url}" # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') getIdForDocument: (document) -> hostname = url.parse(@site.url).hostname date = document.date.toISOString().split('T')[0] path = document.url "tag:#{hostname},#{date},#{path}" fixLinks: (content) -> baseUrl = @site.url regex = /^(http|https|ftp|mailto):/ $ = cheerio.load(content) $('img').each -> $img = $(@) src = $img.attr('src') $img.attr('src', baseUrl + src) unless regex.test(src) $('a').each -> $a = $(@) href = $a.attr('href') $a.attr('href', baseUrl + href) unless regex.test(href) $.html() getTagUrl: (tag) -> slug = tag.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') "/tags/#{slug}/" # Disus.com settings disqusShortName: 'dorajistyle-static' # Google+ settings googlePlusId: '111183731766919710839' # ================================= # Collections # These are special collections that our website makes available to us collections: # pages: (database) -> # database.findAllLive({pageTest: $exists: true}, [pageTest:1,title:1]) # posts: (database) -> # database.findAllLive({tags:$has:'post'}, [date:-1]) '여행': -> @getCollection('html').findAllLive({relativeOutDirPath: '여행'}, [title:1]) '준비': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['여행','준비'].join('/') }, [{date: -1}] ) '대한민국': -> @getCollection('html').findAllLive({relativeOutDirPath: '대한민국'}, [title:1]) '서울': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','서울'].join('/') }, [{date: -1}] ) '인천': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','인천'].join('/') }, [{date: -1}] ) '대전': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','대전'].join('/') }, [{date: -1}] ) '대구': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','대구'].join('/') }, [{date: -1}] ) '울산': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','울산'].join('/') }, [{date: -1}] ) '광주': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','광주'].join('/') }, [{date: -1}] ) '부산': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','부산'].join('/') }, [{date: -1}] ) '경기도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경기도'].join('/') }, [{date: -1}] ) '강원도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','강원도'].join('/') }, [{date: -1}] ) '충청남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','충청남도'].join('/') }, [{date: -1}] ) '충청북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','충청북도'].join('/') }, [{date: -1}] ) '전라남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','전라남도'].join('/') }, [{date: -1}] ) '전라북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','전라북도'].join('/') }, [{date: -1}] ) '경상남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경상남도'].join('/') }, [{date: -1}] ) '경상북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경상북도'].join('/') }, [{date: -1}] ) '제주도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','제주도'].join('/') }, [{date: -1}] ) '유럽': -> @getCollection('html').findAllLive({relativeOutDirPath: '유럽'}, [title:1]) '이탈리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','이탈리아'].join('/') }, [{date: -1}] ) '스페인': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','스페인'].join('/') }, [{date: -1}] ) '프랑스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','프랑스'].join('/') }, [{date: -1}] ) '독일': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','독일'].join('/') }, [{date: -1}] ) '영국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','영국'].join('/') }, [{date: -1}] ) '아일랜드': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','아일랜드'].join('/') }, [{date: -1}] ) '노르웨이': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','노르웨이'].join('/') }, [{date: -1}] ) '스웨덴': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','스웨덴'].join('/') }, [{date: -1}] ) '오스트리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','오스트리아'].join('/') }, [{date: -1}] ) '헝가리': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','헝가리'].join('/') }, [{date: -1}] ) '슬로바키아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','슬로바키아'].join('/') }, [{date: -1}] ) '아시아': -> @getCollection('html').findAllLive({relativeOutDirPath: '아시아'}, [title:1]) '중국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','중국'].join('/') }, [{date: -1}] ) '일본': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','일본'].join('/') }, [{date: -1}] ) '태국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','태국'].join('/') }, [{date: -1}] ) '라오스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','라오스'].join('/') }, [{date: -1}] ) '베트남': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','베트남'].join('/') }, [{date: -1}] ) '말레이시아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','말레이시아'].join('/') }, [{date: -1}] ) '필리핀': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','필리핀'].join('/') }, [{date: -1}] ) '중동': -> @getCollection('html').findAllLive({relativeOutDirPath: '중동'}, [title:1]) '터키': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','터키'].join('/') }, [{date: -1}] ) '시리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','시리아'].join('/') }, [{date: -1}] ) '요르단': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','요르단'].join('/') }, [{date: -1}] ) '아프리카': -> @getCollection('html').findAllLive({relativeOutDirPath: '아프리카'}, [title:1]) '이집트': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아프리카','이집트'].join('/') }, [{date: -1}] ) '북미': -> @getCollection('html').findAllLive({relativeOutDirPath: '북미'}, [title:1]) '미국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['북미','미국'].join('/') }, [{date: -1}] ) '캐나다': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['북미','캐나다'].join('/') }, [{date: -1}] ) '남미': -> @getCollection('html').findAllLive({relativeOutDirPath: '남미'}, [title:1]) '오세아니아': -> @getCollection('html').findAllLive({relativeOutDirPath: '오세아니아'}, [title:1]) '책': -> @getCollection('html').findAllLive({relativeOutDirPath: '책'}, [title:1]) '수필': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','수필'].join('/') }, [{date: -1}] ) '소설': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','소설'].join('/') }, [{date: -1}] ) '희곡': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','희곡'].join('/') }, [{date: -1}] ) '시': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','시'].join('/') }, [{date: -1}] ) '철학': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','철학'].join('/') }, [{date: -1}] ) '건강비결': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','건강비결'].join('/') }, [{date: -1}] ) '사회': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','사회'].join('/') }, [{date: -1}] ) '창작기술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','창작기술'].join('/') }, [{date: -1}] ) '자기계발': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','자기계발'].join('/') }, [{date: -1}] ) '기술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','기술'].join('/') }, [{date: -1}] ) '기타_책': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','기타_책'].join('/') }, [{date: -1}] ) '지식': -> @getCollection('html').findAllLive({relativeOutDirPath: '지식'}, [title:1]) '언어': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','언어'].join('/') }, [{date: -1}] ) '인문학': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','인문학'].join('/') }, [{date: -1}] ) '기타_지식': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','기타_지식'].join('/') }, [{date: -1}] ) '건강': -> @getCollection('html').findAllLive({relativeOutDirPath: '건강'}, [title:1]) '식사': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','식사'].join('/') }, [{date: -1}] ) '운동': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','운동'].join('/') }, [{date: -1}] ) '명상': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','상상'].join('/') }, [{date: -1}] ) '기타_건강': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','기타_건강'].join('/') }, [{date: -1}] ) '영화': -> @getCollection('html').findAllLive({relativeOutDirPath: '영화'}, [title:1]) '한국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','한국영화'].join('/') }, [{date: -1}] ) '영국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','영국영화'].join('/') }, [{date: -1}] ) '미국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','미국영화'].join('/') }, [{date: -1}] ) '프랑스영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','프랑스영화'].join('/') }, [{date: -1}] ) '이탈리아영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','이탈리아영화'].join('/') }, [{date: -1}] ) '스웨덴영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','스웨덴영화'].join('/') }, [{date: -1}] ) '독일영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','독일영화'].join('/') }, [{date: -1}] ) '루마니아영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','루마니아영화'].join('/') }, [{date: -1}] ) '홍콩영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','홍콩영화'].join('/') }, [{date: -1}] ) '인도영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','인도영화'].join('/') }, [{date: -1}] ) '드라마': -> @getCollection('html').findAllLive({relativeOutDirPath: '드라마'}, [title:1]) '국내': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['드라마','국내'].join('/') }, [{date: -1}] ) '국외': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['드라마','국외'].join('/') }, [{date: -1}] ) '음악': -> @getCollection('html').findAllLive({relativeOutDirPath: '음악'}, [title:1]) '재즈': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','재즈'].join('/') }, [{date: -1}] ) '록': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','록'].join('/') }, [{date: -1}] ) '힙합': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','힙합'].join('/') }, [{date: -1}] ) '팝': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','팝'].join('/') }, [{date: -1}] ) '어쿠스틱': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','어쿠스틱'].join('/') }, [{date: -1}] ) '트랜스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','트랜스'].join('/') }, [{date: -1}] ) '기타_음악': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','기타_음악'].join('/') }, [{date: -1}] ) '문화': -> @getCollection('html').findAllLive({relativeOutDirPath: '문화'}, [title:1]) '연극': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','연극'].join('/') }, [{date: -1}] ) '뮤지컬': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','뮤지컬'].join('/') }, [{date: -1}] ) '음악회': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','음악회'].join('/') }, [{date: -1}] ) '춤': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','춤'].join('/') }, [{date: -1}] ) '전시': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','전시'].join('/') }, [{date: -1}] ) '콘퍼런스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','콘퍼런스'].join('/') }, [{date: -1}] ) '조리법': -> @getCollection('html').findAllLive({relativeOutDirPath: '조리법'}, [title:1]) '요리': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','요리'].join('/') }, [{date: -1}] ) '활동식': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','활동식'].join('/') }, [{date: -1}] ) '음료': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','음료'].join('/') }, [{date: -1}] ) '사용기': -> @getCollection('html').findAllLive({relativeOutDirPath: '사용기'}, [title:1]) '전자제품': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','전자제품'].join('/') }, [{date: -1}] ) '음향': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','음향'].join('/') }, [{date: -1}] ) '기타_사용기': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','기타_사용기'].join('/') }, [{date: -1}] ) '동물': -> @getCollection('html').findAllLive({relativeOutDirPath: '동물'}, [title:1]) '고양이': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['동물','고양이'].join('/') }, [{date: -1}] ) 'IT': -> @getCollection('html').findAllLive({relativeOutDirPath: 'IT'}, [title:1]) 'web': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','web'].join('/') }, [{date: -1}] ) 'db': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','db'].join('/') }, [{date: -1}] ) 'sccm': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','sccm'].join('/') }, [{date: -1}] ) 'testing': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','testing'].join('/') }, [{date: -1}] ) 'blog': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','blog'].join('/') }, [{date: -1}] ) 'OS': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','OS'].join('/') }, [{date: -1}] ) '3D': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','3D'].join('/') }, [{date: -1}] ) 'development': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','development'].join('/') }, [{date: -1}] ) 'mobile': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','mobile'].join('/') }, [{date: -1}] ) '환경': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','환경'].join('/') }, [{date: -1}] ) '이론': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','이론'].join('/') }, [{date: -1}] ) 'tip': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','tip'].join('/') }, [{date: -1}] ) 'app': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','app'].join('/') }, [{date: -1}] ) 'etc': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','etc'].join('/') }, [{date: -1}] ) '취미': -> @getCollection('html').findAllLive({relativeOutDirPath: '취미'}, [title:1]) '사진': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','사진'].join('/') }, [{date: -1}] ) '자전거': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','자전거'].join('/') }, [{date: -1}] ) '무술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','무술'].join('/') }, [{date: -1}] ) '수영': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','수영'].join('/') }, [{date: -1}] ) '다이빙': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','다이빙'].join('/') }, [{date: -1}] ) '음주가무': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','음주가무'].join('/') }, [{date: -1}] ) '월풍': -> @getCollection('html').findAllLive({relativeOutDirPath: '월풍'}, [title:1]) '독백': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','독백'].join('/') }, [{date: -1}] ) '일기': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','일기'].join('/') }, [{date: -1}] ) '사유': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','사유'].join('/') }, [{date: -1}] ) '창작': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','창작'].join('/') }, [{date: -1}] ) '삶': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','삶'].join('/') }, [{date: -1}] ) # Configure Plugins # Should contain the plugin short names on the left, and the configuration to pass the plugin on the right #watchOptions: # interval: 2007 # preferredMethods: ['watchFile','watch'] watchOptions: null plugins: moment: formats: [ {raw: 'date', format: 'MMMM Do YYYY', formatted: 'humanDate'} {raw: 'date', format: 'YYYY-MM-DD', formatted: 'computerDate'} ] ghpages: deployRemote: 'target' deployBranch: 'master' # tags: # findCollectionName: '대한민국' # extension: '.html' # injectDocumentHelper: (document) -> # document.setMeta( # layout: 'tags' # ) #livereload: # enabled: false # ================================= # DocPad Events # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req,res,next) -> if req.headers.host in oldUrls res.redirect(newUrl+req.url, 301) else next() } # Candidate of collections generator # for main of categories # docpadConfig.collections[main] = -> # @getCollection("html").findAllLive # relativeOutDirPath: main # , [title: 1] # for sub of categories[main] # docpadConfig.collections[categories[main][sub]] = -> # @getCollection("html").findAllLive # relativeOutDirPath: [ # main # categories[main][sub] # ].join("/") # isPagedAuto: # $ne: true # , [date: -1] # for sub of categories[main] # docpadConfig.collections[categories[main][sub]] = -> # @getCollection('html').findAllLive({ # relativeOutDirPath: [main,categories[main][sub]].join('/') # }, [{date: -1}] # ) # Export our DocPad Configuration module.exports = docpadConfig
141595
cheerio = require('cheerio') url = require('url') categories = { '여행': ['준비'], '대한민국': ['서울','인천','부산','경기도','강원도','충청남도','충청북도','전라남도','전라북도','경상남도','경상북도','제주도'], # '대한민국': ['서울','인천','대전','대구','울산','광주','부산','경기도','강원도','충청남도','충청북도','전라남도','전라북도','경상남도','경상북도','제주도'], '유럽': ['이탈리아','스페인','프랑스','독일','영국','아일랜드','노르웨이','스웨덴','오스트리아','헝가리','슬로바키아'], '아시아': ['중국','일본','태국','라오스','베트남','말레이시아','필리핀'], '중동': ['터키','시리아','요르단'], '아프리카': ['이집트'], '북미': ['미국','캐나다'], '남미': [], '오세아니아': [], '책': ['수필','소설','희곡','시','철학','건강비결','사회','창작기술','자기계발','기술','기타_책'], '지식': ['언어','인문학','기타_지식'], '건강': ['식사','운동','명상','기타_건강'], '영화': ['한국영화','영국영화','미국영화','프랑스영화','이탈리아영화','스웨덴영화','독일영화','루마니아영화','홍콩영화','인도영화'], '드라마': ['국내','국외'], '음악': ['재즈','록','힙합','팝','어쿠스틱','트랜스','기타_음악'], '문화': ['연극','뮤지컬','음악회','춤','전시','콘퍼런스'], '조리법': ['요리','활동식','음료'], '사용기': ['전자제품', '음향', '기타_사용기'], '동물': ['고양이'], 'IT': ['web','db','sccm','testing','blog', 'OS','3D','development','mobile','환경','이론','tip','app','etc'], '취미': ['사진', '자전거','무술','수영','다이빙', '음주가무'], '월풍': ['독백','일기','사유','창작','삶'] } # The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON docpadConfig = { #envirnments: # static: # plugins: # cleanurls: # static: true # trailingSlashes: false # ================================= # Template Data # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: # Specify some site properties site: # The production url of our website url: "http://dorajistyle.net" # Here are some old site urls that you would like to redirect from oldUrls: [ 'http://dorajistyle.net' ] # The default title of our website title: "월풍도원(月風道院) STATIC Version - Delight on the Simple Life" # The website description (for SEO) description: """ 방랑자의 이야기 STATIC 버전.(STATIC version of stories about vagabond.) """ # The website keywords (for SEO) separated by commas keywords: """ 여행,명상,철학,방랑,행복,인생,IT,vagabond,travel,trip,meditation,philosophy,happiness,life """ # The website author's name author: "<NAME>" # The website author's email email: "<EMAIL>" # Styles styles: [ "http://yui.yahooapis.com/pure/0.3.0/pure-min.css" "http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" "/styles/style.css" ] # Scripts scripts: [ "/scripts/main.js" ] # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description getPageUrlWithHostname: -> "#{@site.url}#{@document.url}" # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') getIdForDocument: (document) -> hostname = url.parse(@site.url).hostname date = document.date.toISOString().split('T')[0] path = document.url "tag:#{hostname},#{date},#{path}" fixLinks: (content) -> baseUrl = @site.url regex = /^(http|https|ftp|mailto):/ $ = cheerio.load(content) $('img').each -> $img = $(@) src = $img.attr('src') $img.attr('src', baseUrl + src) unless regex.test(src) $('a').each -> $a = $(@) href = $a.attr('href') $a.attr('href', baseUrl + href) unless regex.test(href) $.html() getTagUrl: (tag) -> slug = tag.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') "/tags/#{slug}/" # Disus.com settings disqusShortName: 'dorajistyle-static' # Google+ settings googlePlusId: '111183731766919710839' # ================================= # Collections # These are special collections that our website makes available to us collections: # pages: (database) -> # database.findAllLive({pageTest: $exists: true}, [pageTest:1,title:1]) # posts: (database) -> # database.findAllLive({tags:$has:'post'}, [date:-1]) '여행': -> @getCollection('html').findAllLive({relativeOutDirPath: '여행'}, [title:1]) '준비': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['여행','준비'].join('/') }, [{date: -1}] ) '대한민국': -> @getCollection('html').findAllLive({relativeOutDirPath: '대한민국'}, [title:1]) '서울': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','서울'].join('/') }, [{date: -1}] ) '인천': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','인천'].join('/') }, [{date: -1}] ) '대전': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','대전'].join('/') }, [{date: -1}] ) '대구': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','대구'].join('/') }, [{date: -1}] ) '울산': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','울산'].join('/') }, [{date: -1}] ) '광주': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','광주'].join('/') }, [{date: -1}] ) '부산': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','부산'].join('/') }, [{date: -1}] ) '경기도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경기도'].join('/') }, [{date: -1}] ) '강원도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','강원도'].join('/') }, [{date: -1}] ) '충청남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','충청남도'].join('/') }, [{date: -1}] ) '충청북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','충청북도'].join('/') }, [{date: -1}] ) '전라남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','전라남도'].join('/') }, [{date: -1}] ) '전라북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','전라북도'].join('/') }, [{date: -1}] ) '경상남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경상남도'].join('/') }, [{date: -1}] ) '경상북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경상북도'].join('/') }, [{date: -1}] ) '제주도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','제주도'].join('/') }, [{date: -1}] ) '유럽': -> @getCollection('html').findAllLive({relativeOutDirPath: '유럽'}, [title:1]) '이탈리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','이탈리아'].join('/') }, [{date: -1}] ) '스페인': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','스페인'].join('/') }, [{date: -1}] ) '프랑스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','프랑스'].join('/') }, [{date: -1}] ) '독일': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','독일'].join('/') }, [{date: -1}] ) '영국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','영국'].join('/') }, [{date: -1}] ) '아일랜드': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','아일랜드'].join('/') }, [{date: -1}] ) '노르웨이': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','노르웨이'].join('/') }, [{date: -1}] ) '스웨덴': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','스웨덴'].join('/') }, [{date: -1}] ) '오스트리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','오스트리아'].join('/') }, [{date: -1}] ) '헝가리': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','헝가리'].join('/') }, [{date: -1}] ) '슬로바키아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','슬로바키아'].join('/') }, [{date: -1}] ) '아시아': -> @getCollection('html').findAllLive({relativeOutDirPath: '아시아'}, [title:1]) '중국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','중국'].join('/') }, [{date: -1}] ) '일본': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','일본'].join('/') }, [{date: -1}] ) '태국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','태국'].join('/') }, [{date: -1}] ) '라오스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','라오스'].join('/') }, [{date: -1}] ) '베트남': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','베트남'].join('/') }, [{date: -1}] ) '말레이시아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','말레이시아'].join('/') }, [{date: -1}] ) '필리핀': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','필리핀'].join('/') }, [{date: -1}] ) '중동': -> @getCollection('html').findAllLive({relativeOutDirPath: '중동'}, [title:1]) '터키': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','터키'].join('/') }, [{date: -1}] ) '시리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','시리아'].join('/') }, [{date: -1}] ) '요르단': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','요르단'].join('/') }, [{date: -1}] ) '아프리카': -> @getCollection('html').findAllLive({relativeOutDirPath: '아프리카'}, [title:1]) '이집트': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아프리카','이집트'].join('/') }, [{date: -1}] ) '북미': -> @getCollection('html').findAllLive({relativeOutDirPath: '북미'}, [title:1]) '미국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['북미','미국'].join('/') }, [{date: -1}] ) '캐나다': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['북미','캐나다'].join('/') }, [{date: -1}] ) '남미': -> @getCollection('html').findAllLive({relativeOutDirPath: '남미'}, [title:1]) '오세아니아': -> @getCollection('html').findAllLive({relativeOutDirPath: '오세아니아'}, [title:1]) '책': -> @getCollection('html').findAllLive({relativeOutDirPath: '책'}, [title:1]) '수필': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','수필'].join('/') }, [{date: -1}] ) '소설': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','소설'].join('/') }, [{date: -1}] ) '희곡': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','희곡'].join('/') }, [{date: -1}] ) '시': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','시'].join('/') }, [{date: -1}] ) '철학': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','철학'].join('/') }, [{date: -1}] ) '건강비결': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','건강비결'].join('/') }, [{date: -1}] ) '사회': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','사회'].join('/') }, [{date: -1}] ) '창작기술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','창작기술'].join('/') }, [{date: -1}] ) '자기계발': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','자기계발'].join('/') }, [{date: -1}] ) '기술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','기술'].join('/') }, [{date: -1}] ) '기타_책': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','기타_책'].join('/') }, [{date: -1}] ) '지식': -> @getCollection('html').findAllLive({relativeOutDirPath: '지식'}, [title:1]) '언어': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','언어'].join('/') }, [{date: -1}] ) '인문학': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','인문학'].join('/') }, [{date: -1}] ) '기타_지식': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','기타_지식'].join('/') }, [{date: -1}] ) '건강': -> @getCollection('html').findAllLive({relativeOutDirPath: '건강'}, [title:1]) '식사': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','식사'].join('/') }, [{date: -1}] ) '운동': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','운동'].join('/') }, [{date: -1}] ) '명상': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','상상'].join('/') }, [{date: -1}] ) '기타_건강': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','기타_건강'].join('/') }, [{date: -1}] ) '영화': -> @getCollection('html').findAllLive({relativeOutDirPath: '영화'}, [title:1]) '한국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','한국영화'].join('/') }, [{date: -1}] ) '영국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','영국영화'].join('/') }, [{date: -1}] ) '미국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','미국영화'].join('/') }, [{date: -1}] ) '프랑스영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','프랑스영화'].join('/') }, [{date: -1}] ) '이탈리아영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','이탈리아영화'].join('/') }, [{date: -1}] ) '스웨덴영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','스웨덴영화'].join('/') }, [{date: -1}] ) '독일영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','독일영화'].join('/') }, [{date: -1}] ) '루마니아영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','루마니아영화'].join('/') }, [{date: -1}] ) '홍콩영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','홍콩영화'].join('/') }, [{date: -1}] ) '인도영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','인도영화'].join('/') }, [{date: -1}] ) '드라마': -> @getCollection('html').findAllLive({relativeOutDirPath: '드라마'}, [title:1]) '국내': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['드라마','국내'].join('/') }, [{date: -1}] ) '국외': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['드라마','국외'].join('/') }, [{date: -1}] ) '음악': -> @getCollection('html').findAllLive({relativeOutDirPath: '음악'}, [title:1]) '재즈': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','재즈'].join('/') }, [{date: -1}] ) '록': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','록'].join('/') }, [{date: -1}] ) '힙합': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','힙합'].join('/') }, [{date: -1}] ) '팝': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','팝'].join('/') }, [{date: -1}] ) '어쿠스틱': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','어쿠스틱'].join('/') }, [{date: -1}] ) '트랜스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','트랜스'].join('/') }, [{date: -1}] ) '기타_음악': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','기타_음악'].join('/') }, [{date: -1}] ) '문화': -> @getCollection('html').findAllLive({relativeOutDirPath: '문화'}, [title:1]) '연극': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','연극'].join('/') }, [{date: -1}] ) '뮤지컬': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','뮤지컬'].join('/') }, [{date: -1}] ) '음악회': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','음악회'].join('/') }, [{date: -1}] ) '춤': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','춤'].join('/') }, [{date: -1}] ) '전시': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','전시'].join('/') }, [{date: -1}] ) '콘퍼런스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','콘퍼런스'].join('/') }, [{date: -1}] ) '조리법': -> @getCollection('html').findAllLive({relativeOutDirPath: '조리법'}, [title:1]) '요리': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','요리'].join('/') }, [{date: -1}] ) '활동식': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','활동식'].join('/') }, [{date: -1}] ) '음료': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','음료'].join('/') }, [{date: -1}] ) '사용기': -> @getCollection('html').findAllLive({relativeOutDirPath: '사용기'}, [title:1]) '전자제품': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','전자제품'].join('/') }, [{date: -1}] ) '음향': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','음향'].join('/') }, [{date: -1}] ) '기타_사용기': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','기타_사용기'].join('/') }, [{date: -1}] ) '동물': -> @getCollection('html').findAllLive({relativeOutDirPath: '동물'}, [title:1]) '고양이': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['동물','고양이'].join('/') }, [{date: -1}] ) 'IT': -> @getCollection('html').findAllLive({relativeOutDirPath: 'IT'}, [title:1]) 'web': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','web'].join('/') }, [{date: -1}] ) 'db': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','db'].join('/') }, [{date: -1}] ) 'sccm': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','sccm'].join('/') }, [{date: -1}] ) 'testing': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','testing'].join('/') }, [{date: -1}] ) 'blog': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','blog'].join('/') }, [{date: -1}] ) 'OS': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','OS'].join('/') }, [{date: -1}] ) '3D': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','3D'].join('/') }, [{date: -1}] ) 'development': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','development'].join('/') }, [{date: -1}] ) 'mobile': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','mobile'].join('/') }, [{date: -1}] ) '환경': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','환경'].join('/') }, [{date: -1}] ) '이론': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','이론'].join('/') }, [{date: -1}] ) 'tip': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','tip'].join('/') }, [{date: -1}] ) 'app': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','app'].join('/') }, [{date: -1}] ) 'etc': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','etc'].join('/') }, [{date: -1}] ) '취미': -> @getCollection('html').findAllLive({relativeOutDirPath: '취미'}, [title:1]) '사진': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','사진'].join('/') }, [{date: -1}] ) '자전거': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','자전거'].join('/') }, [{date: -1}] ) '무술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','무술'].join('/') }, [{date: -1}] ) '수영': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','수영'].join('/') }, [{date: -1}] ) '다이빙': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','다이빙'].join('/') }, [{date: -1}] ) '음주가무': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','음주가무'].join('/') }, [{date: -1}] ) '월풍': -> @getCollection('html').findAllLive({relativeOutDirPath: '월풍'}, [title:1]) '독백': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','독백'].join('/') }, [{date: -1}] ) '일기': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','일기'].join('/') }, [{date: -1}] ) '사유': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','사유'].join('/') }, [{date: -1}] ) '창작': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','창작'].join('/') }, [{date: -1}] ) '삶': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','삶'].join('/') }, [{date: -1}] ) # Configure Plugins # Should contain the plugin short names on the left, and the configuration to pass the plugin on the right #watchOptions: # interval: 2007 # preferredMethods: ['watchFile','watch'] watchOptions: null plugins: moment: formats: [ {raw: 'date', format: 'MMMM Do YYYY', formatted: 'humanDate'} {raw: 'date', format: 'YYYY-MM-DD', formatted: 'computerDate'} ] ghpages: deployRemote: 'target' deployBranch: 'master' # tags: # findCollectionName: '대한민국' # extension: '.html' # injectDocumentHelper: (document) -> # document.setMeta( # layout: 'tags' # ) #livereload: # enabled: false # ================================= # DocPad Events # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req,res,next) -> if req.headers.host in oldUrls res.redirect(newUrl+req.url, 301) else next() } # Candidate of collections generator # for main of categories # docpadConfig.collections[main] = -> # @getCollection("html").findAllLive # relativeOutDirPath: main # , [title: 1] # for sub of categories[main] # docpadConfig.collections[categories[main][sub]] = -> # @getCollection("html").findAllLive # relativeOutDirPath: [ # main # categories[main][sub] # ].join("/") # isPagedAuto: # $ne: true # , [date: -1] # for sub of categories[main] # docpadConfig.collections[categories[main][sub]] = -> # @getCollection('html').findAllLive({ # relativeOutDirPath: [main,categories[main][sub]].join('/') # }, [{date: -1}] # ) # Export our DocPad Configuration module.exports = docpadConfig
true
cheerio = require('cheerio') url = require('url') categories = { '여행': ['준비'], '대한민국': ['서울','인천','부산','경기도','강원도','충청남도','충청북도','전라남도','전라북도','경상남도','경상북도','제주도'], # '대한민국': ['서울','인천','대전','대구','울산','광주','부산','경기도','강원도','충청남도','충청북도','전라남도','전라북도','경상남도','경상북도','제주도'], '유럽': ['이탈리아','스페인','프랑스','독일','영국','아일랜드','노르웨이','스웨덴','오스트리아','헝가리','슬로바키아'], '아시아': ['중국','일본','태국','라오스','베트남','말레이시아','필리핀'], '중동': ['터키','시리아','요르단'], '아프리카': ['이집트'], '북미': ['미국','캐나다'], '남미': [], '오세아니아': [], '책': ['수필','소설','희곡','시','철학','건강비결','사회','창작기술','자기계발','기술','기타_책'], '지식': ['언어','인문학','기타_지식'], '건강': ['식사','운동','명상','기타_건강'], '영화': ['한국영화','영국영화','미국영화','프랑스영화','이탈리아영화','스웨덴영화','독일영화','루마니아영화','홍콩영화','인도영화'], '드라마': ['국내','국외'], '음악': ['재즈','록','힙합','팝','어쿠스틱','트랜스','기타_음악'], '문화': ['연극','뮤지컬','음악회','춤','전시','콘퍼런스'], '조리법': ['요리','활동식','음료'], '사용기': ['전자제품', '음향', '기타_사용기'], '동물': ['고양이'], 'IT': ['web','db','sccm','testing','blog', 'OS','3D','development','mobile','환경','이론','tip','app','etc'], '취미': ['사진', '자전거','무술','수영','다이빙', '음주가무'], '월풍': ['독백','일기','사유','창작','삶'] } # The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON docpadConfig = { #envirnments: # static: # plugins: # cleanurls: # static: true # trailingSlashes: false # ================================= # Template Data # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: # Specify some site properties site: # The production url of our website url: "http://dorajistyle.net" # Here are some old site urls that you would like to redirect from oldUrls: [ 'http://dorajistyle.net' ] # The default title of our website title: "월풍도원(月風道院) STATIC Version - Delight on the Simple Life" # The website description (for SEO) description: """ 방랑자의 이야기 STATIC 버전.(STATIC version of stories about vagabond.) """ # The website keywords (for SEO) separated by commas keywords: """ 여행,명상,철학,방랑,행복,인생,IT,vagabond,travel,trip,meditation,philosophy,happiness,life """ # The website author's name author: "PI:NAME:<NAME>END_PI" # The website author's email email: "PI:EMAIL:<EMAIL>END_PI" # Styles styles: [ "http://yui.yahooapis.com/pure/0.3.0/pure-min.css" "http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" "/styles/style.css" ] # Scripts scripts: [ "/scripts/main.js" ] # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description getPageUrlWithHostname: -> "#{@site.url}#{@document.url}" # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') getIdForDocument: (document) -> hostname = url.parse(@site.url).hostname date = document.date.toISOString().split('T')[0] path = document.url "tag:#{hostname},#{date},#{path}" fixLinks: (content) -> baseUrl = @site.url regex = /^(http|https|ftp|mailto):/ $ = cheerio.load(content) $('img').each -> $img = $(@) src = $img.attr('src') $img.attr('src', baseUrl + src) unless regex.test(src) $('a').each -> $a = $(@) href = $a.attr('href') $a.attr('href', baseUrl + href) unless regex.test(href) $.html() getTagUrl: (tag) -> slug = tag.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') "/tags/#{slug}/" # Disus.com settings disqusShortName: 'dorajistyle-static' # Google+ settings googlePlusId: '111183731766919710839' # ================================= # Collections # These are special collections that our website makes available to us collections: # pages: (database) -> # database.findAllLive({pageTest: $exists: true}, [pageTest:1,title:1]) # posts: (database) -> # database.findAllLive({tags:$has:'post'}, [date:-1]) '여행': -> @getCollection('html').findAllLive({relativeOutDirPath: '여행'}, [title:1]) '준비': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['여행','준비'].join('/') }, [{date: -1}] ) '대한민국': -> @getCollection('html').findAllLive({relativeOutDirPath: '대한민국'}, [title:1]) '서울': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','서울'].join('/') }, [{date: -1}] ) '인천': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','인천'].join('/') }, [{date: -1}] ) '대전': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','대전'].join('/') }, [{date: -1}] ) '대구': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','대구'].join('/') }, [{date: -1}] ) '울산': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','울산'].join('/') }, [{date: -1}] ) '광주': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','광주'].join('/') }, [{date: -1}] ) '부산': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','부산'].join('/') }, [{date: -1}] ) '경기도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경기도'].join('/') }, [{date: -1}] ) '강원도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','강원도'].join('/') }, [{date: -1}] ) '충청남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','충청남도'].join('/') }, [{date: -1}] ) '충청북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','충청북도'].join('/') }, [{date: -1}] ) '전라남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','전라남도'].join('/') }, [{date: -1}] ) '전라북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','전라북도'].join('/') }, [{date: -1}] ) '경상남도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경상남도'].join('/') }, [{date: -1}] ) '경상북도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','경상북도'].join('/') }, [{date: -1}] ) '제주도': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['대한민국','제주도'].join('/') }, [{date: -1}] ) '유럽': -> @getCollection('html').findAllLive({relativeOutDirPath: '유럽'}, [title:1]) '이탈리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','이탈리아'].join('/') }, [{date: -1}] ) '스페인': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','스페인'].join('/') }, [{date: -1}] ) '프랑스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','프랑스'].join('/') }, [{date: -1}] ) '독일': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','독일'].join('/') }, [{date: -1}] ) '영국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','영국'].join('/') }, [{date: -1}] ) '아일랜드': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','아일랜드'].join('/') }, [{date: -1}] ) '노르웨이': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','노르웨이'].join('/') }, [{date: -1}] ) '스웨덴': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','스웨덴'].join('/') }, [{date: -1}] ) '오스트리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','오스트리아'].join('/') }, [{date: -1}] ) '헝가리': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','헝가리'].join('/') }, [{date: -1}] ) '슬로바키아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['유럽','슬로바키아'].join('/') }, [{date: -1}] ) '아시아': -> @getCollection('html').findAllLive({relativeOutDirPath: '아시아'}, [title:1]) '중국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','중국'].join('/') }, [{date: -1}] ) '일본': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','일본'].join('/') }, [{date: -1}] ) '태국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','태국'].join('/') }, [{date: -1}] ) '라오스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','라오스'].join('/') }, [{date: -1}] ) '베트남': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','베트남'].join('/') }, [{date: -1}] ) '말레이시아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','말레이시아'].join('/') }, [{date: -1}] ) '필리핀': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아시아','필리핀'].join('/') }, [{date: -1}] ) '중동': -> @getCollection('html').findAllLive({relativeOutDirPath: '중동'}, [title:1]) '터키': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','터키'].join('/') }, [{date: -1}] ) '시리아': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','시리아'].join('/') }, [{date: -1}] ) '요르단': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['중동','요르단'].join('/') }, [{date: -1}] ) '아프리카': -> @getCollection('html').findAllLive({relativeOutDirPath: '아프리카'}, [title:1]) '이집트': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['아프리카','이집트'].join('/') }, [{date: -1}] ) '북미': -> @getCollection('html').findAllLive({relativeOutDirPath: '북미'}, [title:1]) '미국': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['북미','미국'].join('/') }, [{date: -1}] ) '캐나다': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['북미','캐나다'].join('/') }, [{date: -1}] ) '남미': -> @getCollection('html').findAllLive({relativeOutDirPath: '남미'}, [title:1]) '오세아니아': -> @getCollection('html').findAllLive({relativeOutDirPath: '오세아니아'}, [title:1]) '책': -> @getCollection('html').findAllLive({relativeOutDirPath: '책'}, [title:1]) '수필': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','수필'].join('/') }, [{date: -1}] ) '소설': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','소설'].join('/') }, [{date: -1}] ) '희곡': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','희곡'].join('/') }, [{date: -1}] ) '시': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','시'].join('/') }, [{date: -1}] ) '철학': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','철학'].join('/') }, [{date: -1}] ) '건강비결': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','건강비결'].join('/') }, [{date: -1}] ) '사회': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','사회'].join('/') }, [{date: -1}] ) '창작기술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','창작기술'].join('/') }, [{date: -1}] ) '자기계발': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','자기계발'].join('/') }, [{date: -1}] ) '기술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','기술'].join('/') }, [{date: -1}] ) '기타_책': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['책','기타_책'].join('/') }, [{date: -1}] ) '지식': -> @getCollection('html').findAllLive({relativeOutDirPath: '지식'}, [title:1]) '언어': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','언어'].join('/') }, [{date: -1}] ) '인문학': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','인문학'].join('/') }, [{date: -1}] ) '기타_지식': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['지식','기타_지식'].join('/') }, [{date: -1}] ) '건강': -> @getCollection('html').findAllLive({relativeOutDirPath: '건강'}, [title:1]) '식사': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','식사'].join('/') }, [{date: -1}] ) '운동': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','운동'].join('/') }, [{date: -1}] ) '명상': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','상상'].join('/') }, [{date: -1}] ) '기타_건강': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['건강','기타_건강'].join('/') }, [{date: -1}] ) '영화': -> @getCollection('html').findAllLive({relativeOutDirPath: '영화'}, [title:1]) '한국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','한국영화'].join('/') }, [{date: -1}] ) '영국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','영국영화'].join('/') }, [{date: -1}] ) '미국영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','미국영화'].join('/') }, [{date: -1}] ) '프랑스영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','프랑스영화'].join('/') }, [{date: -1}] ) '이탈리아영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','이탈리아영화'].join('/') }, [{date: -1}] ) '스웨덴영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','스웨덴영화'].join('/') }, [{date: -1}] ) '독일영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','독일영화'].join('/') }, [{date: -1}] ) '루마니아영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','루마니아영화'].join('/') }, [{date: -1}] ) '홍콩영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','홍콩영화'].join('/') }, [{date: -1}] ) '인도영화': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['영화','인도영화'].join('/') }, [{date: -1}] ) '드라마': -> @getCollection('html').findAllLive({relativeOutDirPath: '드라마'}, [title:1]) '국내': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['드라마','국내'].join('/') }, [{date: -1}] ) '국외': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['드라마','국외'].join('/') }, [{date: -1}] ) '음악': -> @getCollection('html').findAllLive({relativeOutDirPath: '음악'}, [title:1]) '재즈': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','재즈'].join('/') }, [{date: -1}] ) '록': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','록'].join('/') }, [{date: -1}] ) '힙합': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','힙합'].join('/') }, [{date: -1}] ) '팝': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','팝'].join('/') }, [{date: -1}] ) '어쿠스틱': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','어쿠스틱'].join('/') }, [{date: -1}] ) '트랜스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','트랜스'].join('/') }, [{date: -1}] ) '기타_음악': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['음악','기타_음악'].join('/') }, [{date: -1}] ) '문화': -> @getCollection('html').findAllLive({relativeOutDirPath: '문화'}, [title:1]) '연극': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','연극'].join('/') }, [{date: -1}] ) '뮤지컬': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','뮤지컬'].join('/') }, [{date: -1}] ) '음악회': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','음악회'].join('/') }, [{date: -1}] ) '춤': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','춤'].join('/') }, [{date: -1}] ) '전시': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','전시'].join('/') }, [{date: -1}] ) '콘퍼런스': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['문화','콘퍼런스'].join('/') }, [{date: -1}] ) '조리법': -> @getCollection('html').findAllLive({relativeOutDirPath: '조리법'}, [title:1]) '요리': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','요리'].join('/') }, [{date: -1}] ) '활동식': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','활동식'].join('/') }, [{date: -1}] ) '음료': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['조리법','음료'].join('/') }, [{date: -1}] ) '사용기': -> @getCollection('html').findAllLive({relativeOutDirPath: '사용기'}, [title:1]) '전자제품': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','전자제품'].join('/') }, [{date: -1}] ) '음향': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','음향'].join('/') }, [{date: -1}] ) '기타_사용기': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['사용기','기타_사용기'].join('/') }, [{date: -1}] ) '동물': -> @getCollection('html').findAllLive({relativeOutDirPath: '동물'}, [title:1]) '고양이': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['동물','고양이'].join('/') }, [{date: -1}] ) 'IT': -> @getCollection('html').findAllLive({relativeOutDirPath: 'IT'}, [title:1]) 'web': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','web'].join('/') }, [{date: -1}] ) 'db': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','db'].join('/') }, [{date: -1}] ) 'sccm': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','sccm'].join('/') }, [{date: -1}] ) 'testing': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','testing'].join('/') }, [{date: -1}] ) 'blog': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','blog'].join('/') }, [{date: -1}] ) 'OS': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','OS'].join('/') }, [{date: -1}] ) '3D': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','3D'].join('/') }, [{date: -1}] ) 'development': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','development'].join('/') }, [{date: -1}] ) 'mobile': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','mobile'].join('/') }, [{date: -1}] ) '환경': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','환경'].join('/') }, [{date: -1}] ) '이론': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','이론'].join('/') }, [{date: -1}] ) 'tip': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','tip'].join('/') }, [{date: -1}] ) 'app': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','app'].join('/') }, [{date: -1}] ) 'etc': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['IT','etc'].join('/') }, [{date: -1}] ) '취미': -> @getCollection('html').findAllLive({relativeOutDirPath: '취미'}, [title:1]) '사진': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','사진'].join('/') }, [{date: -1}] ) '자전거': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','자전거'].join('/') }, [{date: -1}] ) '무술': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','무술'].join('/') }, [{date: -1}] ) '수영': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','수영'].join('/') }, [{date: -1}] ) '다이빙': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','다이빙'].join('/') }, [{date: -1}] ) '음주가무': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['취미','음주가무'].join('/') }, [{date: -1}] ) '월풍': -> @getCollection('html').findAllLive({relativeOutDirPath: '월풍'}, [title:1]) '독백': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','독백'].join('/') }, [{date: -1}] ) '일기': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','일기'].join('/') }, [{date: -1}] ) '사유': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','사유'].join('/') }, [{date: -1}] ) '창작': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','창작'].join('/') }, [{date: -1}] ) '삶': -> @getCollection('html').findAllLive({ relativeOutDirPath: ['월풍','삶'].join('/') }, [{date: -1}] ) # Configure Plugins # Should contain the plugin short names on the left, and the configuration to pass the plugin on the right #watchOptions: # interval: 2007 # preferredMethods: ['watchFile','watch'] watchOptions: null plugins: moment: formats: [ {raw: 'date', format: 'MMMM Do YYYY', formatted: 'humanDate'} {raw: 'date', format: 'YYYY-MM-DD', formatted: 'computerDate'} ] ghpages: deployRemote: 'target' deployBranch: 'master' # tags: # findCollectionName: '대한민국' # extension: '.html' # injectDocumentHelper: (document) -> # document.setMeta( # layout: 'tags' # ) #livereload: # enabled: false # ================================= # DocPad Events # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req,res,next) -> if req.headers.host in oldUrls res.redirect(newUrl+req.url, 301) else next() } # Candidate of collections generator # for main of categories # docpadConfig.collections[main] = -> # @getCollection("html").findAllLive # relativeOutDirPath: main # , [title: 1] # for sub of categories[main] # docpadConfig.collections[categories[main][sub]] = -> # @getCollection("html").findAllLive # relativeOutDirPath: [ # main # categories[main][sub] # ].join("/") # isPagedAuto: # $ne: true # , [date: -1] # for sub of categories[main] # docpadConfig.collections[categories[main][sub]] = -> # @getCollection('html').findAllLive({ # relativeOutDirPath: [main,categories[main][sub]].join('/') # }, [{date: -1}] # ) # Export our DocPad Configuration module.exports = docpadConfig
[ { "context": "constants\"\n\n.constant \"firebaseConfig\",\n\tapiKey: \"AIzaSyC84FRJ5B4fs1ZqHwFjv7uhQ3rr3NaFJ-c\"\n\tauthDomain: \"tracker-9c7c9.firebaseapp.com\"\n\tda", "end": 123, "score": 0.9997727870941162, "start": 84, "tag": "KEY", "value": "AIzaSyC84FRJ5B4fs1ZqHwFjv7uhQ3rr3NaFJ-c" }, { "context": "63827\"\n\n.constant \"firebaseTestConfig\",\n\tapiKey: \"fake-api-key-for-testing-purposes-only\"\n\tdatabaseURL: \"ws://test.fi", "end": 390, "score": 0.9669911861419678, "start": 373, "tag": "KEY", "value": "fake-api-key-for-" }, { "context": "aseTestConfig\",\n\tapiKey: \"fake-api-key-for-testing-purposes-only\"\n\tdatabaseURL: \"ws://test.firebaseio.localhost:50", "end": 411, "score": 0.9280899167060852, "start": 398, "tag": "KEY", "value": "purposes-only" }, { "context": "NVALID_EMAIL: \"Invalid email\"\n\tINVALID_PASSWORD: \"Invalid password\"\n\tINVALID_CATEGORY_ID: \"Invalid category id\"\n\tDAT", "end": 1126, "score": 0.9989917874336243, "start": 1110, "tag": "PASSWORD", "value": "Invalid password" }, { "context": "T_FOUND: \"auth/user-not-found\"\n\t\tWRONG_PASSWORD: \"auth/wrong-password\"\n\tregister:\n\t\tINVALID_EMAIL: \"auth/invalid-email\"", "end": 1518, "score": 0.9995098114013672, "start": 1499, "tag": "PASSWORD", "value": "auth/wrong-password" }, { "context": "D: \"auth/operation-not-allowed\"\n\t\tWEAK_PASSWORD: \"auth/weak-password\"\n\n.constant \"overrideCacheService\", true\n", "end": 1711, "score": 0.9995023608207703, "start": 1693, "tag": "PASSWORD", "value": "auth/weak-password" } ]
app/src/constants.coffee
jimmynguyen/tracker
0
"use strict" angular.module "app.constants" .constant "firebaseConfig", apiKey: "AIzaSyC84FRJ5B4fs1ZqHwFjv7uhQ3rr3NaFJ-c" authDomain: "tracker-9c7c9.firebaseapp.com" databaseURL: "https://tracker-9c7c9.firebaseio.com" projectId: "tracker-9c7c9" storageBucket: "tracker-9c7c9.appspot.com" messagingSenderId: "542245163827" .constant "firebaseTestConfig", apiKey: "fake-api-key-for-testing-purposes-only" databaseURL: "ws://test.firebaseio.localhost:5000" .constant "keys", system: default: data_types: "system/default/data_types" fields: "system/default/fields" definition: account: "system/definition/account" category: "system/definition/category" data_type: "system/definition/data_type" dropdown: "system/definition/dropdown" field: "system/definition/field" user: accounts: "user/accounts" categories: "user/categories" data_types: "user/data_types" entries: "user/entries" selected: category: "selected/category" entry: "selected/entry" app: dataTypeIdMap: "app/dataTypeIdMap" .constant "errors", INVALID_EMAIL: "Invalid email" INVALID_PASSWORD: "Invalid password" INVALID_CATEGORY_ID: "Invalid category id" DATABASE_SERVICE_INITIALIZATION: "Error during DatabaseService initialization" .constant "errorTypes", AUTHENTICATION_ERROR: "Authentication Error" .constant "firebaseErrorCodes", login: INVALID_EMAIL: "auth/invalid-email" USER_DISABLED: "auth/user-disabled" USER_NOT_FOUND: "auth/user-not-found" WRONG_PASSWORD: "auth/wrong-password" register: INVALID_EMAIL: "auth/invalid-email" EMAIL_ALREADY_IN_USE: "auth/email-already-in-use" OPERATION_NOT_ALLOWED: "auth/operation-not-allowed" WEAK_PASSWORD: "auth/weak-password" .constant "overrideCacheService", true
183909
"use strict" angular.module "app.constants" .constant "firebaseConfig", apiKey: "<KEY>" authDomain: "tracker-9c7c9.firebaseapp.com" databaseURL: "https://tracker-9c7c9.firebaseio.com" projectId: "tracker-9c7c9" storageBucket: "tracker-9c7c9.appspot.com" messagingSenderId: "542245163827" .constant "firebaseTestConfig", apiKey: "<KEY>testing-<KEY>" databaseURL: "ws://test.firebaseio.localhost:5000" .constant "keys", system: default: data_types: "system/default/data_types" fields: "system/default/fields" definition: account: "system/definition/account" category: "system/definition/category" data_type: "system/definition/data_type" dropdown: "system/definition/dropdown" field: "system/definition/field" user: accounts: "user/accounts" categories: "user/categories" data_types: "user/data_types" entries: "user/entries" selected: category: "selected/category" entry: "selected/entry" app: dataTypeIdMap: "app/dataTypeIdMap" .constant "errors", INVALID_EMAIL: "Invalid email" INVALID_PASSWORD: "<PASSWORD>" INVALID_CATEGORY_ID: "Invalid category id" DATABASE_SERVICE_INITIALIZATION: "Error during DatabaseService initialization" .constant "errorTypes", AUTHENTICATION_ERROR: "Authentication Error" .constant "firebaseErrorCodes", login: INVALID_EMAIL: "auth/invalid-email" USER_DISABLED: "auth/user-disabled" USER_NOT_FOUND: "auth/user-not-found" WRONG_PASSWORD: "<PASSWORD>" register: INVALID_EMAIL: "auth/invalid-email" EMAIL_ALREADY_IN_USE: "auth/email-already-in-use" OPERATION_NOT_ALLOWED: "auth/operation-not-allowed" WEAK_PASSWORD: "<PASSWORD>" .constant "overrideCacheService", true
true
"use strict" angular.module "app.constants" .constant "firebaseConfig", apiKey: "PI:KEY:<KEY>END_PI" authDomain: "tracker-9c7c9.firebaseapp.com" databaseURL: "https://tracker-9c7c9.firebaseio.com" projectId: "tracker-9c7c9" storageBucket: "tracker-9c7c9.appspot.com" messagingSenderId: "542245163827" .constant "firebaseTestConfig", apiKey: "PI:KEY:<KEY>END_PItesting-PI:KEY:<KEY>END_PI" databaseURL: "ws://test.firebaseio.localhost:5000" .constant "keys", system: default: data_types: "system/default/data_types" fields: "system/default/fields" definition: account: "system/definition/account" category: "system/definition/category" data_type: "system/definition/data_type" dropdown: "system/definition/dropdown" field: "system/definition/field" user: accounts: "user/accounts" categories: "user/categories" data_types: "user/data_types" entries: "user/entries" selected: category: "selected/category" entry: "selected/entry" app: dataTypeIdMap: "app/dataTypeIdMap" .constant "errors", INVALID_EMAIL: "Invalid email" INVALID_PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" INVALID_CATEGORY_ID: "Invalid category id" DATABASE_SERVICE_INITIALIZATION: "Error during DatabaseService initialization" .constant "errorTypes", AUTHENTICATION_ERROR: "Authentication Error" .constant "firebaseErrorCodes", login: INVALID_EMAIL: "auth/invalid-email" USER_DISABLED: "auth/user-disabled" USER_NOT_FOUND: "auth/user-not-found" WRONG_PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" register: INVALID_EMAIL: "auth/invalid-email" EMAIL_ALREADY_IN_USE: "auth/email-already-in-use" OPERATION_NOT_ALLOWED: "auth/operation-not-allowed" WEAK_PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" .constant "overrideCacheService", true
[ { "context": " # - Spanish: es_es (credit: https://github.com/bomberstudios)\n #\n constructor: (locale) ->\n @i18n = local", "end": 795, "score": 0.9995426535606384, "start": 782, "tag": "USERNAME", "value": "bomberstudios" }, { "context": ": =>\n switch @i18n\n when \"es_es\"\n \"Derecha\"\n else\n \"Right\"\n\n uiVerticalFirst: =", "end": 3303, "score": 0.7325336337089539, "start": 3296, "tag": "NAME", "value": "Derecha" } ]
src/documents/guideguide/js/lib/GuideGuideMessages.js.coffee
Acidburn0zzz/core-1
0
# The Messages class makes it possible to provide GuideGuide in multiple # languages. English is used by default if a translation does not exist for the # i18n string provided. To add a new language, add a new `when` block for the # desired i18n string that returns the translated string. For methods that # include dynamic data, be sure to include the dynamic data. # # Usage: # var messages = new Messages "en_us" # console.log messages.makeGrid() # # Make grid # # Styleguide # - Use sentence case for titles. # class window.GuideGuideMessages # Create a Messages object and set the language to be used. # # locale - locale code for language of choice # # Currently supported locale: # - English: en_us # - Spanish: es_es (credit: https://github.com/bomberstudios) # constructor: (locale) -> @i18n = locale if locale? # # UI Messages # These messages are generally titles and button labels. # uiGrid: => switch @i18n when "es_es" "Retícula" else "Grid" uiCustom: => switch @i18n when "es_es" "Personalizada" else "Custom" uiSets: => switch @i18n when "es_es" "Sets" else "Sets" uiUpdates: => switch @i18n when "es_es" "Actualizaciones" else "Updates" uiDebug: => switch @i18n when "es_es" "Debug" else "Debug" uiMakeGrid: => switch @i18n when "es_es" "Crear retícula" else "Make grid" uiSaveSet: => switch @i18n when "es_es" "Guardar set" else "Save set" uiSaveSettings: => switch @i18n when "es_es" "Guardar ajustes" else "Save settings" uiImport: => switch @i18n when "es_es" "Importar" else "Import" uiExport: => switch @i18n when "es_es" "Exportar" else "Export" uiOk: => switch @i18n when "es_es" "Ok" else "Ok" uiCancel: => switch @i18n when "es_es" "Cancelar" else "Cancel" uiDonate: => switch @i18n when "es_es" "Donar" else "Donate" uiCheckForUpdates: => switch @i18n when "es_es" "Buscar actualizaciones" else "Check for updates" uiShowLogs: => switch @i18n when "es_es" "Mostrar logs" else "Show logs" uiHorizontalPosition: => switch @i18n when "es_es" "Posición horizontal" else "Horizontal position" uiVerticalPosition: => switch @i18n when "es_es" "Posición vertical" else "Vertical position" uiHorizontalRemainder: => switch @i18n when "es_es" "Resto horizontal" else "Horizontal remainder" uiVerticalRemainder: => switch @i18n when "es_es" "Resto vertical" else "Vertical remainder" uiHorizontalFirst: => switch @i18n when "es_es" "Izquierda" else "Left" uiHorizontalCenter: => switch @i18n when "es_es" "Centro" else "Center" uiHorizontalLast: => switch @i18n when "es_es" "Derecha" else "Right" uiVerticalFirst: => switch @i18n when "es_es" "Arriba" else "Top" uiVerticalCenter: => switch @i18n when "es_es" "Centro" else "Center" uiVerticalLast: => switch @i18n when "es_es" "Abajo" else "Bottom" uiYes: => switch @i18n when "es_es" "Si" else "Yes" uiNo: => switch @i18n when "es_es" "No" else "No" uiNiceNo: => switch @i18n when "es_es" "No, gracias" else "No thanks" uiOpenInBrowser: => switch @i18n when "es_es" "Abrir en navegador" else "Open in browser" # # Help Messages # These are essentially tooltips. They appear in the UI to explain features. # helpPosition: => switch @i18n when "es_es" "Determina dónde coloca GuideGuide una retícula cuando es más pequeña que el área disponible." else "This determines where GuideGuide puts a grid when it is smaller than the available area." helpRemainder: => switch @i18n when "es_es" "En modo pixel, GuideGuide redondea hacia abajo los anchos con píxeles decimales y usa este ajuste para determinar qué columnas o filas reciben los pixels sobrantes." else "In pixel mode, GuideGuide rounds down decimal pixel widths and uses this setting to determine which columns or rows receive the remainder pixels." helpImportDesc: => switch @i18n when "es_es" "Importa sets pegando una url de GitHub Gist en el campo de texto de abajo." else "Import sets by pasting a GitHub Gist url in the text field below." helpGistExport: => switch @i18n when "es_es" 'Estos son los datos de un set de guías exportado por el plugin GuideGuide. Para importarlos, haz click en el botón "Importar" en los ajustes de GuideGuide y pega la url de este Gist, o el contenido del fichero `sets.json` en el campo de texto.' else 'This is guide set data exported by the GuideGuide plugin. To import them, click the "Import" button in the GuideGuide settings and paste this Gist url, or the contents of `sets.json` into the text field.' helpImportExport: => switch @i18n when "es_es" "GuideGuide importa y exporta sus datos mediante" else "GuideGuide imports and exports its data via" # # Alert Messages # These are titles and messages for alert dialogues. # alertTitleWelcome: => switch @i18n when "es_es" "Bienvenido a GuideGuide" else "Welcome to GuideGuide" alertTitleUpToDate: => switch @i18n when "es_es" "Estás al día" else "Up to date" alertMessageUpToDate: => switch @i18n when "es_es" "Ya tienes la última versión de GuideGuide." else "GuideGuide is currently up to date." alertTitleUpdateError: => switch @i18n when "es_es" "Error buscando actualizaciones" else "Error checking for updates" alertMessageUpdateError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de buscar actualizaciones en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to check for updates at this time. Please try again later." alertTitleUpdate: => "Updates available" alertMessageUpdate: => "Update GuideGuide to get the latest version." alertTitleImportSuccess: => switch @i18n when "es_es" "Sets importados" else "Sets imported" alertMessageImportSuccess: => switch @i18n when "es_es" "Tus sets se han importado correctamente." else "Your sets have successfully been imported." alertTitleImportGistError: => switch @i18n when "es_es" "Error de Importación" else "Import Error" alertMessageImportGistError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de importar sets en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to import sets at this time. Please try again later." alertTitleImportGistNoSets: => switch @i18n when "es_es" "Error de Importación" else "Import error" alertMessageImportGistNoSets: => switch @i18n when "es_es" "GuideGuide no ha sido capaz de encontrar sets.json en este Gist." else "GuideGuide was not able to find sets.json in this Gist." alertTitleImportNotGist: => switch @i18n when "es_es" "Error de Importación" else "Import Error" alertMessageImportNotGist: => switch @i18n when "es_es" "El texto de entrada no contiene una url de GitHub Gist." else "The input text does not contain a GitHub Gist url." alertTitleExportSuccess: => switch @i18n when "es_es" "Sets exportados" else "Sets have been exported" alertMessageExportSuccess: (url) => button = "<div><strong><a class='js-link button export-button' href='#{ url }'>#{ @uiOpenInBrowser() }</a></strong></div>" switch @i18n when "es_es" "Tus sets han sido exportados a un GitHub Gist secreto. #{ button }" else "Your sets have been exported to a secret GitHub Gist. #{ button }" alertTitleExportError: => switch @i18n when "es_es" "Imposible exportar" else "Unable to export" alertMessageExportError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de exportar sets en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to export sets at this time. Please try again later." alertTitleDonate: => switch @i18n when "es_es" "¿Te gustaría donar?" else "Would you like to donate?" alertMessageDonate: => switch @i18n when "es_es" "¡Vaya, ya has usado GuideGuide 30 veces! Parece que le estás sacando bastante partido a GuideGuide, ¿te interesaría hacer una donación para contribuir a su desarrollo?" else "Yowza, you've used GuideGuide 30 times! Since you seem to get quite a bit of use out of GuideGuide, would you consider making a donation to the development?" # # GuideGuide Notation messages # These messages appear in the Custom field # gapUnrecognized: => switch @i18n when "es_es" "Hueco no reconocido" else "Unrecognized gap" gapNoFillWildcards: => switch @i18n when "es_es" "Los comodines no pueden ser rellenos" else "Wildcards cannot be fills" ggnNoGrids: => switch @i18n when "es_es" "Esta cadena no contiene ninguna retícula" else "This string does not contain any grids" ggnFillInVariable: => switch @i18n when "es_es" "Las variables no pueden contener un relleno" else "Variables cannot contain a fill" ggnNoWildcardsInVariableFills: => switch @i18n when "es_es" "Una variable usada como relleno no puede contener un comodín" else "A variable used as a fill can not contain a wildcard" ggnUndefinedVariable: => switch @i18n when "es_es" "Variable no definida" else "Undefined variable" ggnOneFillPerGrid: => switch @i18n when "es_es" "Una retícula sólo puede contener un relleno" else "A grid can only contain one fill" ggnMoreThanOneHundredPercent: => switch @i18n when "es_es" "Una retícula no puede contener más del 100%" else "A grid cannot contain more than 100%" ggnStringFromExistingGuides: => switch @i18n when "es_es" "Cadena generada a partir de las guías existentes" else "String generated from existing guides"
8855
# The Messages class makes it possible to provide GuideGuide in multiple # languages. English is used by default if a translation does not exist for the # i18n string provided. To add a new language, add a new `when` block for the # desired i18n string that returns the translated string. For methods that # include dynamic data, be sure to include the dynamic data. # # Usage: # var messages = new Messages "en_us" # console.log messages.makeGrid() # # Make grid # # Styleguide # - Use sentence case for titles. # class window.GuideGuideMessages # Create a Messages object and set the language to be used. # # locale - locale code for language of choice # # Currently supported locale: # - English: en_us # - Spanish: es_es (credit: https://github.com/bomberstudios) # constructor: (locale) -> @i18n = locale if locale? # # UI Messages # These messages are generally titles and button labels. # uiGrid: => switch @i18n when "es_es" "Retícula" else "Grid" uiCustom: => switch @i18n when "es_es" "Personalizada" else "Custom" uiSets: => switch @i18n when "es_es" "Sets" else "Sets" uiUpdates: => switch @i18n when "es_es" "Actualizaciones" else "Updates" uiDebug: => switch @i18n when "es_es" "Debug" else "Debug" uiMakeGrid: => switch @i18n when "es_es" "Crear retícula" else "Make grid" uiSaveSet: => switch @i18n when "es_es" "Guardar set" else "Save set" uiSaveSettings: => switch @i18n when "es_es" "Guardar ajustes" else "Save settings" uiImport: => switch @i18n when "es_es" "Importar" else "Import" uiExport: => switch @i18n when "es_es" "Exportar" else "Export" uiOk: => switch @i18n when "es_es" "Ok" else "Ok" uiCancel: => switch @i18n when "es_es" "Cancelar" else "Cancel" uiDonate: => switch @i18n when "es_es" "Donar" else "Donate" uiCheckForUpdates: => switch @i18n when "es_es" "Buscar actualizaciones" else "Check for updates" uiShowLogs: => switch @i18n when "es_es" "Mostrar logs" else "Show logs" uiHorizontalPosition: => switch @i18n when "es_es" "Posición horizontal" else "Horizontal position" uiVerticalPosition: => switch @i18n when "es_es" "Posición vertical" else "Vertical position" uiHorizontalRemainder: => switch @i18n when "es_es" "Resto horizontal" else "Horizontal remainder" uiVerticalRemainder: => switch @i18n when "es_es" "Resto vertical" else "Vertical remainder" uiHorizontalFirst: => switch @i18n when "es_es" "Izquierda" else "Left" uiHorizontalCenter: => switch @i18n when "es_es" "Centro" else "Center" uiHorizontalLast: => switch @i18n when "es_es" "<NAME>" else "Right" uiVerticalFirst: => switch @i18n when "es_es" "Arriba" else "Top" uiVerticalCenter: => switch @i18n when "es_es" "Centro" else "Center" uiVerticalLast: => switch @i18n when "es_es" "Abajo" else "Bottom" uiYes: => switch @i18n when "es_es" "Si" else "Yes" uiNo: => switch @i18n when "es_es" "No" else "No" uiNiceNo: => switch @i18n when "es_es" "No, gracias" else "No thanks" uiOpenInBrowser: => switch @i18n when "es_es" "Abrir en navegador" else "Open in browser" # # Help Messages # These are essentially tooltips. They appear in the UI to explain features. # helpPosition: => switch @i18n when "es_es" "Determina dónde coloca GuideGuide una retícula cuando es más pequeña que el área disponible." else "This determines where GuideGuide puts a grid when it is smaller than the available area." helpRemainder: => switch @i18n when "es_es" "En modo pixel, GuideGuide redondea hacia abajo los anchos con píxeles decimales y usa este ajuste para determinar qué columnas o filas reciben los pixels sobrantes." else "In pixel mode, GuideGuide rounds down decimal pixel widths and uses this setting to determine which columns or rows receive the remainder pixels." helpImportDesc: => switch @i18n when "es_es" "Importa sets pegando una url de GitHub Gist en el campo de texto de abajo." else "Import sets by pasting a GitHub Gist url in the text field below." helpGistExport: => switch @i18n when "es_es" 'Estos son los datos de un set de guías exportado por el plugin GuideGuide. Para importarlos, haz click en el botón "Importar" en los ajustes de GuideGuide y pega la url de este Gist, o el contenido del fichero `sets.json` en el campo de texto.' else 'This is guide set data exported by the GuideGuide plugin. To import them, click the "Import" button in the GuideGuide settings and paste this Gist url, or the contents of `sets.json` into the text field.' helpImportExport: => switch @i18n when "es_es" "GuideGuide importa y exporta sus datos mediante" else "GuideGuide imports and exports its data via" # # Alert Messages # These are titles and messages for alert dialogues. # alertTitleWelcome: => switch @i18n when "es_es" "Bienvenido a GuideGuide" else "Welcome to GuideGuide" alertTitleUpToDate: => switch @i18n when "es_es" "Estás al día" else "Up to date" alertMessageUpToDate: => switch @i18n when "es_es" "Ya tienes la última versión de GuideGuide." else "GuideGuide is currently up to date." alertTitleUpdateError: => switch @i18n when "es_es" "Error buscando actualizaciones" else "Error checking for updates" alertMessageUpdateError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de buscar actualizaciones en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to check for updates at this time. Please try again later." alertTitleUpdate: => "Updates available" alertMessageUpdate: => "Update GuideGuide to get the latest version." alertTitleImportSuccess: => switch @i18n when "es_es" "Sets importados" else "Sets imported" alertMessageImportSuccess: => switch @i18n when "es_es" "Tus sets se han importado correctamente." else "Your sets have successfully been imported." alertTitleImportGistError: => switch @i18n when "es_es" "Error de Importación" else "Import Error" alertMessageImportGistError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de importar sets en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to import sets at this time. Please try again later." alertTitleImportGistNoSets: => switch @i18n when "es_es" "Error de Importación" else "Import error" alertMessageImportGistNoSets: => switch @i18n when "es_es" "GuideGuide no ha sido capaz de encontrar sets.json en este Gist." else "GuideGuide was not able to find sets.json in this Gist." alertTitleImportNotGist: => switch @i18n when "es_es" "Error de Importación" else "Import Error" alertMessageImportNotGist: => switch @i18n when "es_es" "El texto de entrada no contiene una url de GitHub Gist." else "The input text does not contain a GitHub Gist url." alertTitleExportSuccess: => switch @i18n when "es_es" "Sets exportados" else "Sets have been exported" alertMessageExportSuccess: (url) => button = "<div><strong><a class='js-link button export-button' href='#{ url }'>#{ @uiOpenInBrowser() }</a></strong></div>" switch @i18n when "es_es" "Tus sets han sido exportados a un GitHub Gist secreto. #{ button }" else "Your sets have been exported to a secret GitHub Gist. #{ button }" alertTitleExportError: => switch @i18n when "es_es" "Imposible exportar" else "Unable to export" alertMessageExportError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de exportar sets en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to export sets at this time. Please try again later." alertTitleDonate: => switch @i18n when "es_es" "¿Te gustaría donar?" else "Would you like to donate?" alertMessageDonate: => switch @i18n when "es_es" "¡Vaya, ya has usado GuideGuide 30 veces! Parece que le estás sacando bastante partido a GuideGuide, ¿te interesaría hacer una donación para contribuir a su desarrollo?" else "Yowza, you've used GuideGuide 30 times! Since you seem to get quite a bit of use out of GuideGuide, would you consider making a donation to the development?" # # GuideGuide Notation messages # These messages appear in the Custom field # gapUnrecognized: => switch @i18n when "es_es" "Hueco no reconocido" else "Unrecognized gap" gapNoFillWildcards: => switch @i18n when "es_es" "Los comodines no pueden ser rellenos" else "Wildcards cannot be fills" ggnNoGrids: => switch @i18n when "es_es" "Esta cadena no contiene ninguna retícula" else "This string does not contain any grids" ggnFillInVariable: => switch @i18n when "es_es" "Las variables no pueden contener un relleno" else "Variables cannot contain a fill" ggnNoWildcardsInVariableFills: => switch @i18n when "es_es" "Una variable usada como relleno no puede contener un comodín" else "A variable used as a fill can not contain a wildcard" ggnUndefinedVariable: => switch @i18n when "es_es" "Variable no definida" else "Undefined variable" ggnOneFillPerGrid: => switch @i18n when "es_es" "Una retícula sólo puede contener un relleno" else "A grid can only contain one fill" ggnMoreThanOneHundredPercent: => switch @i18n when "es_es" "Una retícula no puede contener más del 100%" else "A grid cannot contain more than 100%" ggnStringFromExistingGuides: => switch @i18n when "es_es" "Cadena generada a partir de las guías existentes" else "String generated from existing guides"
true
# The Messages class makes it possible to provide GuideGuide in multiple # languages. English is used by default if a translation does not exist for the # i18n string provided. To add a new language, add a new `when` block for the # desired i18n string that returns the translated string. For methods that # include dynamic data, be sure to include the dynamic data. # # Usage: # var messages = new Messages "en_us" # console.log messages.makeGrid() # # Make grid # # Styleguide # - Use sentence case for titles. # class window.GuideGuideMessages # Create a Messages object and set the language to be used. # # locale - locale code for language of choice # # Currently supported locale: # - English: en_us # - Spanish: es_es (credit: https://github.com/bomberstudios) # constructor: (locale) -> @i18n = locale if locale? # # UI Messages # These messages are generally titles and button labels. # uiGrid: => switch @i18n when "es_es" "Retícula" else "Grid" uiCustom: => switch @i18n when "es_es" "Personalizada" else "Custom" uiSets: => switch @i18n when "es_es" "Sets" else "Sets" uiUpdates: => switch @i18n when "es_es" "Actualizaciones" else "Updates" uiDebug: => switch @i18n when "es_es" "Debug" else "Debug" uiMakeGrid: => switch @i18n when "es_es" "Crear retícula" else "Make grid" uiSaveSet: => switch @i18n when "es_es" "Guardar set" else "Save set" uiSaveSettings: => switch @i18n when "es_es" "Guardar ajustes" else "Save settings" uiImport: => switch @i18n when "es_es" "Importar" else "Import" uiExport: => switch @i18n when "es_es" "Exportar" else "Export" uiOk: => switch @i18n when "es_es" "Ok" else "Ok" uiCancel: => switch @i18n when "es_es" "Cancelar" else "Cancel" uiDonate: => switch @i18n when "es_es" "Donar" else "Donate" uiCheckForUpdates: => switch @i18n when "es_es" "Buscar actualizaciones" else "Check for updates" uiShowLogs: => switch @i18n when "es_es" "Mostrar logs" else "Show logs" uiHorizontalPosition: => switch @i18n when "es_es" "Posición horizontal" else "Horizontal position" uiVerticalPosition: => switch @i18n when "es_es" "Posición vertical" else "Vertical position" uiHorizontalRemainder: => switch @i18n when "es_es" "Resto horizontal" else "Horizontal remainder" uiVerticalRemainder: => switch @i18n when "es_es" "Resto vertical" else "Vertical remainder" uiHorizontalFirst: => switch @i18n when "es_es" "Izquierda" else "Left" uiHorizontalCenter: => switch @i18n when "es_es" "Centro" else "Center" uiHorizontalLast: => switch @i18n when "es_es" "PI:NAME:<NAME>END_PI" else "Right" uiVerticalFirst: => switch @i18n when "es_es" "Arriba" else "Top" uiVerticalCenter: => switch @i18n when "es_es" "Centro" else "Center" uiVerticalLast: => switch @i18n when "es_es" "Abajo" else "Bottom" uiYes: => switch @i18n when "es_es" "Si" else "Yes" uiNo: => switch @i18n when "es_es" "No" else "No" uiNiceNo: => switch @i18n when "es_es" "No, gracias" else "No thanks" uiOpenInBrowser: => switch @i18n when "es_es" "Abrir en navegador" else "Open in browser" # # Help Messages # These are essentially tooltips. They appear in the UI to explain features. # helpPosition: => switch @i18n when "es_es" "Determina dónde coloca GuideGuide una retícula cuando es más pequeña que el área disponible." else "This determines where GuideGuide puts a grid when it is smaller than the available area." helpRemainder: => switch @i18n when "es_es" "En modo pixel, GuideGuide redondea hacia abajo los anchos con píxeles decimales y usa este ajuste para determinar qué columnas o filas reciben los pixels sobrantes." else "In pixel mode, GuideGuide rounds down decimal pixel widths and uses this setting to determine which columns or rows receive the remainder pixels." helpImportDesc: => switch @i18n when "es_es" "Importa sets pegando una url de GitHub Gist en el campo de texto de abajo." else "Import sets by pasting a GitHub Gist url in the text field below." helpGistExport: => switch @i18n when "es_es" 'Estos son los datos de un set de guías exportado por el plugin GuideGuide. Para importarlos, haz click en el botón "Importar" en los ajustes de GuideGuide y pega la url de este Gist, o el contenido del fichero `sets.json` en el campo de texto.' else 'This is guide set data exported by the GuideGuide plugin. To import them, click the "Import" button in the GuideGuide settings and paste this Gist url, or the contents of `sets.json` into the text field.' helpImportExport: => switch @i18n when "es_es" "GuideGuide importa y exporta sus datos mediante" else "GuideGuide imports and exports its data via" # # Alert Messages # These are titles and messages for alert dialogues. # alertTitleWelcome: => switch @i18n when "es_es" "Bienvenido a GuideGuide" else "Welcome to GuideGuide" alertTitleUpToDate: => switch @i18n when "es_es" "Estás al día" else "Up to date" alertMessageUpToDate: => switch @i18n when "es_es" "Ya tienes la última versión de GuideGuide." else "GuideGuide is currently up to date." alertTitleUpdateError: => switch @i18n when "es_es" "Error buscando actualizaciones" else "Error checking for updates" alertMessageUpdateError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de buscar actualizaciones en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to check for updates at this time. Please try again later." alertTitleUpdate: => "Updates available" alertMessageUpdate: => "Update GuideGuide to get the latest version." alertTitleImportSuccess: => switch @i18n when "es_es" "Sets importados" else "Sets imported" alertMessageImportSuccess: => switch @i18n when "es_es" "Tus sets se han importado correctamente." else "Your sets have successfully been imported." alertTitleImportGistError: => switch @i18n when "es_es" "Error de Importación" else "Import Error" alertMessageImportGistError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de importar sets en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to import sets at this time. Please try again later." alertTitleImportGistNoSets: => switch @i18n when "es_es" "Error de Importación" else "Import error" alertMessageImportGistNoSets: => switch @i18n when "es_es" "GuideGuide no ha sido capaz de encontrar sets.json en este Gist." else "GuideGuide was not able to find sets.json in this Gist." alertTitleImportNotGist: => switch @i18n when "es_es" "Error de Importación" else "Import Error" alertMessageImportNotGist: => switch @i18n when "es_es" "El texto de entrada no contiene una url de GitHub Gist." else "The input text does not contain a GitHub Gist url." alertTitleExportSuccess: => switch @i18n when "es_es" "Sets exportados" else "Sets have been exported" alertMessageExportSuccess: (url) => button = "<div><strong><a class='js-link button export-button' href='#{ url }'>#{ @uiOpenInBrowser() }</a></strong></div>" switch @i18n when "es_es" "Tus sets han sido exportados a un GitHub Gist secreto. #{ button }" else "Your sets have been exported to a secret GitHub Gist. #{ button }" alertTitleExportError: => switch @i18n when "es_es" "Imposible exportar" else "Unable to export" alertMessageExportError: => switch @i18n when "es_es" "Desgraciadamente, GuideGuide no ha sido capaz de exportar sets en este momento. Por favor, inténtalo de nuevo más adelante." else "Unfortunately, GuideGuide is unable to export sets at this time. Please try again later." alertTitleDonate: => switch @i18n when "es_es" "¿Te gustaría donar?" else "Would you like to donate?" alertMessageDonate: => switch @i18n when "es_es" "¡Vaya, ya has usado GuideGuide 30 veces! Parece que le estás sacando bastante partido a GuideGuide, ¿te interesaría hacer una donación para contribuir a su desarrollo?" else "Yowza, you've used GuideGuide 30 times! Since you seem to get quite a bit of use out of GuideGuide, would you consider making a donation to the development?" # # GuideGuide Notation messages # These messages appear in the Custom field # gapUnrecognized: => switch @i18n when "es_es" "Hueco no reconocido" else "Unrecognized gap" gapNoFillWildcards: => switch @i18n when "es_es" "Los comodines no pueden ser rellenos" else "Wildcards cannot be fills" ggnNoGrids: => switch @i18n when "es_es" "Esta cadena no contiene ninguna retícula" else "This string does not contain any grids" ggnFillInVariable: => switch @i18n when "es_es" "Las variables no pueden contener un relleno" else "Variables cannot contain a fill" ggnNoWildcardsInVariableFills: => switch @i18n when "es_es" "Una variable usada como relleno no puede contener un comodín" else "A variable used as a fill can not contain a wildcard" ggnUndefinedVariable: => switch @i18n when "es_es" "Variable no definida" else "Undefined variable" ggnOneFillPerGrid: => switch @i18n when "es_es" "Una retícula sólo puede contener un relleno" else "A grid can only contain one fill" ggnMoreThanOneHundredPercent: => switch @i18n when "es_es" "Una retícula no puede contener más del 100%" else "A grid cannot contain more than 100%" ggnStringFromExistingGuides: => switch @i18n when "es_es" "Cadena generada a partir de las guías existentes" else "String generated from existing guides"
[ { "context": "e-1884.firebaseio.com'\n\t.constant 'chainAPIKey', 'aa8318ad204b105287ef578fe9d42966'\n\t.constant 'mandrillAPIKey', 'J0ab-AhedE5pUR1Bbb", "end": 626, "score": 0.9997323751449585, "start": 594, "tag": "KEY", "value": "aa8318ad204b105287ef578fe9d42966" }, { "context": "5287ef578fe9d42966'\n\t.constant 'mandrillAPIKey', 'J0ab-AhedE5pUR1BbbZ7OA'\n\t.constant 'mailchimpAPIKey', '491e9da46f71ad07b", "end": 680, "score": 0.99973064661026, "start": 658, "tag": "KEY", "value": "J0ab-AhedE5pUR1BbbZ7OA" }, { "context": "AhedE5pUR1BbbZ7OA'\n\t.constant 'mailchimpAPIKey', '491e9da46f71ad07bb3d3e1e982c8cf9-us8'\n\t.constant 'dazzleUrl', 'https://swarm.fund' # F", "end": 749, "score": 0.9997411370277405, "start": 713, "tag": "KEY", "value": "491e9da46f71ad07bb3d3e1e982c8cf9-us8" }, { "context": "ytics\n\t\tAngularytics.init()\n\n\t\tfilepicker.setKey 'A6ijVqCLZQoO9LlNEFGxQz'\n\n\t\tStripe.setPublishableKey 'pk_live_mJW1pNhkZnF", "end": 3336, "score": 0.9907960295677185, "start": 3314, "tag": "KEY", "value": "A6ijVqCLZQoO9LlNEFGxQz" }, { "context": "jVqCLZQoO9LlNEFGxQz'\n\n\t\tStripe.setPublishableKey 'pk_live_mJW1pNhkZnFJXsmEXzfFPojV'\n\n\t\t$rootScope.$on '$routeChangeStart', (event, n", "end": 3399, "score": 0.9861049652099609, "start": 3367, "tag": "KEY", "value": "pk_live_mJW1pNhkZnFJXsmEXzfFPojV" } ]
js/dazzle.coffee
SwarmCorp/razzledazzle
0
window.app = angular.module 'Dazzle', ['ngRoute', 'ngAnimate', 'ngSanitize', 'restangular', 'firebase', 'ja.qr', 'angularytics', 'ui.bootstrap.modal', 'ui.bootstrap.datepicker', 'ui.bootstrap.timepicker', 'ui.bootstrap.tpls', 'angular-redactor'] .constant 'discourseUrl', '//discourse.swarm.fund/' .constant 'counterpartyUrl', '//counterwallet.io/_api/' .constant 's3bucket', '//s3.amazonaws.com/swarm.shandro/' .constant 'firebaseUrl', if window.daDebug then 'https://'+window.daDebug.firebase+'.firebaseio.com' else 'https://blinding-fire-1884.firebaseio.com' .constant 'chainAPIKey', 'aa8318ad204b105287ef578fe9d42966' .constant 'mandrillAPIKey', 'J0ab-AhedE5pUR1BbbZ7OA' .constant 'mailchimpAPIKey', '491e9da46f71ad07bb3d3e1e982c8cf9-us8' .constant 'dazzleUrl', 'https://swarm.fund' # FIXME: change to production url .constant 'iOS', if navigator.userAgent.match(/(iPad|iPhone|iPod)/g) then true else false .config ($animateProvider) -> $animateProvider.classNameFilter /da-animate/ .config (RestangularProvider) -> RestangularProvider.setDefaultHeaders 'Content-type': 'text/plain' .config (AngularyticsProvider) -> AngularyticsProvider.setEventHandlers ['GoogleUniversal'] .config (datepickerConfig) -> datepickerConfig.showWeeks = false .config (redactorOptions) -> redactorOptions.buttons = ['formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', '|', 'link'] redactorOptions.formatting = [] redactorOptions.formattingAdd = [{tag: 'p', title: 'Normal text', class: 'text-paragraph'}, {tag: 'h3', title: 'Title', class: 'text-title'}] .factory 'RestRome', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://swarm-rome.herokuapp.com' RestangularConfigurer.setDefaultHeaders 'Content-type': 'application/json' .factory 'RestChain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://api.chain.com/v2/' .factory 'RestSoChain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://chain.so/api/v2/' .factory 'RestBlockscan', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://xcp.blockscan.com/' .factory 'RestBlockchain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://blockchain.info/q' .factory 'RestRazzle', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://razzle.herokuapp.com/api/' .factory 'RestDiscourse', (Restangular, discourseUrl) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl discourseUrl .factory 'RestCounterparty', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://counterparty.swarm.fund/' .factory 'RestMandrill', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://us8.api.mailchimp.com/2.0/' .run ($rootScope, $location, $window, $interval, Angularytics, User, Checkout) -> # Initialize Google Analytics Angularytics.init() filepicker.setKey 'A6ijVqCLZQoO9LlNEFGxQz' Stripe.setPublishableKey 'pk_live_mJW1pNhkZnFJXsmEXzfFPojV' $rootScope.$on '$routeChangeStart', (event, next, current) -> if next?.screenName == 'checkout' projectName = next?.params.project bundleName = next?.params.bundle step = next?.stepName Checkout.set project: projectName bundle: bundleName if !step $location.path('projects/'+projectName+'/'+bundleName+'/checkout/user').replace() $rootScope.$watch () -> User.info.loaded , () -> if !User.isLoggedIn() && !User.info.votingWallet && $location.$$url == '/voting-signup' window.location.href = '/'
61400
window.app = angular.module 'Dazzle', ['ngRoute', 'ngAnimate', 'ngSanitize', 'restangular', 'firebase', 'ja.qr', 'angularytics', 'ui.bootstrap.modal', 'ui.bootstrap.datepicker', 'ui.bootstrap.timepicker', 'ui.bootstrap.tpls', 'angular-redactor'] .constant 'discourseUrl', '//discourse.swarm.fund/' .constant 'counterpartyUrl', '//counterwallet.io/_api/' .constant 's3bucket', '//s3.amazonaws.com/swarm.shandro/' .constant 'firebaseUrl', if window.daDebug then 'https://'+window.daDebug.firebase+'.firebaseio.com' else 'https://blinding-fire-1884.firebaseio.com' .constant 'chainAPIKey', '<KEY>' .constant 'mandrillAPIKey', '<KEY>' .constant 'mailchimpAPIKey', '<KEY>' .constant 'dazzleUrl', 'https://swarm.fund' # FIXME: change to production url .constant 'iOS', if navigator.userAgent.match(/(iPad|iPhone|iPod)/g) then true else false .config ($animateProvider) -> $animateProvider.classNameFilter /da-animate/ .config (RestangularProvider) -> RestangularProvider.setDefaultHeaders 'Content-type': 'text/plain' .config (AngularyticsProvider) -> AngularyticsProvider.setEventHandlers ['GoogleUniversal'] .config (datepickerConfig) -> datepickerConfig.showWeeks = false .config (redactorOptions) -> redactorOptions.buttons = ['formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', '|', 'link'] redactorOptions.formatting = [] redactorOptions.formattingAdd = [{tag: 'p', title: 'Normal text', class: 'text-paragraph'}, {tag: 'h3', title: 'Title', class: 'text-title'}] .factory 'RestRome', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://swarm-rome.herokuapp.com' RestangularConfigurer.setDefaultHeaders 'Content-type': 'application/json' .factory 'RestChain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://api.chain.com/v2/' .factory 'RestSoChain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://chain.so/api/v2/' .factory 'RestBlockscan', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://xcp.blockscan.com/' .factory 'RestBlockchain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://blockchain.info/q' .factory 'RestRazzle', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://razzle.herokuapp.com/api/' .factory 'RestDiscourse', (Restangular, discourseUrl) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl discourseUrl .factory 'RestCounterparty', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://counterparty.swarm.fund/' .factory 'RestMandrill', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://us8.api.mailchimp.com/2.0/' .run ($rootScope, $location, $window, $interval, Angularytics, User, Checkout) -> # Initialize Google Analytics Angularytics.init() filepicker.setKey '<KEY>' Stripe.setPublishableKey '<KEY>' $rootScope.$on '$routeChangeStart', (event, next, current) -> if next?.screenName == 'checkout' projectName = next?.params.project bundleName = next?.params.bundle step = next?.stepName Checkout.set project: projectName bundle: bundleName if !step $location.path('projects/'+projectName+'/'+bundleName+'/checkout/user').replace() $rootScope.$watch () -> User.info.loaded , () -> if !User.isLoggedIn() && !User.info.votingWallet && $location.$$url == '/voting-signup' window.location.href = '/'
true
window.app = angular.module 'Dazzle', ['ngRoute', 'ngAnimate', 'ngSanitize', 'restangular', 'firebase', 'ja.qr', 'angularytics', 'ui.bootstrap.modal', 'ui.bootstrap.datepicker', 'ui.bootstrap.timepicker', 'ui.bootstrap.tpls', 'angular-redactor'] .constant 'discourseUrl', '//discourse.swarm.fund/' .constant 'counterpartyUrl', '//counterwallet.io/_api/' .constant 's3bucket', '//s3.amazonaws.com/swarm.shandro/' .constant 'firebaseUrl', if window.daDebug then 'https://'+window.daDebug.firebase+'.firebaseio.com' else 'https://blinding-fire-1884.firebaseio.com' .constant 'chainAPIKey', 'PI:KEY:<KEY>END_PI' .constant 'mandrillAPIKey', 'PI:KEY:<KEY>END_PI' .constant 'mailchimpAPIKey', 'PI:KEY:<KEY>END_PI' .constant 'dazzleUrl', 'https://swarm.fund' # FIXME: change to production url .constant 'iOS', if navigator.userAgent.match(/(iPad|iPhone|iPod)/g) then true else false .config ($animateProvider) -> $animateProvider.classNameFilter /da-animate/ .config (RestangularProvider) -> RestangularProvider.setDefaultHeaders 'Content-type': 'text/plain' .config (AngularyticsProvider) -> AngularyticsProvider.setEventHandlers ['GoogleUniversal'] .config (datepickerConfig) -> datepickerConfig.showWeeks = false .config (redactorOptions) -> redactorOptions.buttons = ['formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', '|', 'link'] redactorOptions.formatting = [] redactorOptions.formattingAdd = [{tag: 'p', title: 'Normal text', class: 'text-paragraph'}, {tag: 'h3', title: 'Title', class: 'text-title'}] .factory 'RestRome', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://swarm-rome.herokuapp.com' RestangularConfigurer.setDefaultHeaders 'Content-type': 'application/json' .factory 'RestChain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://api.chain.com/v2/' .factory 'RestSoChain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://chain.so/api/v2/' .factory 'RestBlockscan', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://xcp.blockscan.com/' .factory 'RestBlockchain', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://blockchain.info/q' .factory 'RestRazzle', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://razzle.herokuapp.com/api/' .factory 'RestDiscourse', (Restangular, discourseUrl) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl discourseUrl .factory 'RestCounterparty', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://counterparty.swarm.fund/' .factory 'RestMandrill', (Restangular) -> Restangular.withConfig (RestangularConfigurer) -> RestangularConfigurer.setBaseUrl 'https://us8.api.mailchimp.com/2.0/' .run ($rootScope, $location, $window, $interval, Angularytics, User, Checkout) -> # Initialize Google Analytics Angularytics.init() filepicker.setKey 'PI:KEY:<KEY>END_PI' Stripe.setPublishableKey 'PI:KEY:<KEY>END_PI' $rootScope.$on '$routeChangeStart', (event, next, current) -> if next?.screenName == 'checkout' projectName = next?.params.project bundleName = next?.params.bundle step = next?.stepName Checkout.set project: projectName bundle: bundleName if !step $location.path('projects/'+projectName+'/'+bundleName+'/checkout/user').replace() $rootScope.$watch () -> User.info.loaded , () -> if !User.isLoggedIn() && !User.info.votingWallet && $location.$$url == '/voting-signup' window.location.href = '/'
[ { "context": "#### Copyright Paules\n#### Collbot\n\n#### ToDos\n\n# - bei 'live' Bots ver", "end": 21, "score": 0.9991675615310669, "start": 15, "tag": "NAME", "value": "Paules" } ]
bot_collatzesar.coffee
drcollatz/crypto
1
#### Copyright Paules #### Collbot #### ToDos # - bei 'live' Bots verbose automatisch aktivieren # - beim start checken ob bereits eine Position offen ist und evtl. invested=true setzen # - Programmablauf / logging etc neu sortieren # - First Position Strategie? Warten bis zum nächsten Wechsel, oder direkt loslegen? # - Fees berechnen (0.2 % von komplettem Kauf- oder Verkaufswert) # Idee: Ultra Fast Bot 1Min-5Min Ticks... Pro Tag nur wenige aber dafür super safe trades "1% und gut" (bei margin sogar nur 0.4% nötig) -> 30% im Monat. #### START trading = require 'trading' # import core trading module talib = require 'talib' # import technical indicators library (https://cryptotrader.org/talib) _maximumExchangeFee = .20# params.add "Maximum exchange fee %", .25 _maximumOrderAmount = 1 #params.add "Maximum order amount", 1 _orderTimeout = 30 #params.add "Order timeout", 30 class functions #### TA-lib Indicatots @sar: (high, low, lag, accel, accelmax) -> results = talib.SAR high: high low: low startIdx: 0 endIdx: high.length - lag optInAcceleration: accel optInMaximum: accelmax _.last(results) #### Init init: -> context.verbose = true context.live = true context.sarAccel = 0.005 context.sarAccelmax = 0.5 context.sarAccelShort = 0.01 context.sarAccelmaxShort = 0.1 context.positionStatus = "start" context.buyPrice #### Tick execution handle: -> instrument = data.instruments[0] storage.coin ?= data.instruments[0].pair.substring(0, 3).toUpperCase() assetsAvailable = @portfolios[instrument.market].positions[instrument.asset()].amount context.assetsAvailable = assetsAvailable #current assets storage.startAssets ?= assetsAvailable #inital assets currencyAvailable = @portfolios[instrument.market].positions[instrument.curr()].amount context.currencyAvailable = currencyAvailable #current currency storage.startCurrency ?= currencyAvailable #inital currency context.currentPrice = instrument.price storage.startPrice ?= instrument.price #inital price maximumBuyAmount = (currencyAvailable/instrument.price) * (1 - (_maximumExchangeFee/100)) maximumSellAmount = (assetsAvailable * (1 - (_maximumExchangeFee/100))) diff = ((instrument.price / context.buyPrice - 1)*100) ##### Logging if context.verbose debug "Status____________: #{context.positionStatus}" debug "Balance ASSETS____: #{assetsAvailable} #{storage.coin}" debug "Balance CURRENCY__: #{currencyAvailable} USD" debug "Current PRICE_____: #{instrument.price} USD" debug "Current DIFF______: #{diff.toFixed(2)}%" debug "Bot Gewinn________: #{(((context.currencyAvailable + (context.assetsAvailable * context.currentPrice)) / storage.startCurrency - 1)*100).toFixed(2)}%" debug "B&H Gewinn________: #{((context.currentPrice / storage.startPrice - 1)*100).toFixed(2)}%" sarLong = functions.sar(instrument.high, instrument.low, 1,context.sarAccel, context.sarAccelmax) if (diff < -10) ||( diff > 5) && (@portfolio.positions[instrument.asset()].amount > 0) context.positionStatus = "close" warn "EMERGENCY EXIT!" plotMark "stop": 0 plot "sarLong": sarLong switch context.positionStatus when "start" if (sarLong < instrument.price) #long context.positionStatus = "long" warn "LONG" break when "long" if (sarLong > instrument.price) && (context.buyPrice < instrument.price) #close long context.positionStatus = "close" break #### Trading debug "AMOUNT: #{@portfolio.positions[instrument.asset()].amount}" ######## LONG if context.positionStatus == "long" && (@portfolio.positions[instrument.base()].amount > 0) # open long position info "KAUFEN" trading.buy instrument context.buyPrice = instrument.price ######## CLOSE if context.positionStatus == "close" # close long position context.positionStatus = "start" if (@portfolio.positions[instrument.asset()].amount > 0) warn "VERKAUFEN" trading.sell instrument if context.verbose debug "######################################################## " onRestart: -> warn "RESTART DETECTED!!!" onStop: -> debug "######## BOT ENDE ########" debug "Start currency was__: #{storage.startCurrency} USD" debug "End currency is_____: #{context.currencyAvailable} USD" debug "Start asset was_____: #{storage.startAssets} #{storage.coin}" debug "End asset is________: #{context.assetsAvailable} #{storage.coin}" debug "Bot Gewinn__________: #{(((context.currencyAvailable + (context.assetsAvailable * context.currentPrice)) / storage.startCurrency - 1)*100).toFixed(2)}%" debug "B&H Gewinn__________: #{((context.currentPrice / storage.startPrice - 1)*100).toFixed(2)}%"
156663
#### Copyright <NAME> #### Collbot #### ToDos # - bei 'live' Bots verbose automatisch aktivieren # - beim start checken ob bereits eine Position offen ist und evtl. invested=true setzen # - Programmablauf / logging etc neu sortieren # - First Position Strategie? Warten bis zum nächsten Wechsel, oder direkt loslegen? # - Fees berechnen (0.2 % von komplettem Kauf- oder Verkaufswert) # Idee: Ultra Fast Bot 1Min-5Min Ticks... Pro Tag nur wenige aber dafür super safe trades "1% und gut" (bei margin sogar nur 0.4% nötig) -> 30% im Monat. #### START trading = require 'trading' # import core trading module talib = require 'talib' # import technical indicators library (https://cryptotrader.org/talib) _maximumExchangeFee = .20# params.add "Maximum exchange fee %", .25 _maximumOrderAmount = 1 #params.add "Maximum order amount", 1 _orderTimeout = 30 #params.add "Order timeout", 30 class functions #### TA-lib Indicatots @sar: (high, low, lag, accel, accelmax) -> results = talib.SAR high: high low: low startIdx: 0 endIdx: high.length - lag optInAcceleration: accel optInMaximum: accelmax _.last(results) #### Init init: -> context.verbose = true context.live = true context.sarAccel = 0.005 context.sarAccelmax = 0.5 context.sarAccelShort = 0.01 context.sarAccelmaxShort = 0.1 context.positionStatus = "start" context.buyPrice #### Tick execution handle: -> instrument = data.instruments[0] storage.coin ?= data.instruments[0].pair.substring(0, 3).toUpperCase() assetsAvailable = @portfolios[instrument.market].positions[instrument.asset()].amount context.assetsAvailable = assetsAvailable #current assets storage.startAssets ?= assetsAvailable #inital assets currencyAvailable = @portfolios[instrument.market].positions[instrument.curr()].amount context.currencyAvailable = currencyAvailable #current currency storage.startCurrency ?= currencyAvailable #inital currency context.currentPrice = instrument.price storage.startPrice ?= instrument.price #inital price maximumBuyAmount = (currencyAvailable/instrument.price) * (1 - (_maximumExchangeFee/100)) maximumSellAmount = (assetsAvailable * (1 - (_maximumExchangeFee/100))) diff = ((instrument.price / context.buyPrice - 1)*100) ##### Logging if context.verbose debug "Status____________: #{context.positionStatus}" debug "Balance ASSETS____: #{assetsAvailable} #{storage.coin}" debug "Balance CURRENCY__: #{currencyAvailable} USD" debug "Current PRICE_____: #{instrument.price} USD" debug "Current DIFF______: #{diff.toFixed(2)}%" debug "Bot Gewinn________: #{(((context.currencyAvailable + (context.assetsAvailable * context.currentPrice)) / storage.startCurrency - 1)*100).toFixed(2)}%" debug "B&H Gewinn________: #{((context.currentPrice / storage.startPrice - 1)*100).toFixed(2)}%" sarLong = functions.sar(instrument.high, instrument.low, 1,context.sarAccel, context.sarAccelmax) if (diff < -10) ||( diff > 5) && (@portfolio.positions[instrument.asset()].amount > 0) context.positionStatus = "close" warn "EMERGENCY EXIT!" plotMark "stop": 0 plot "sarLong": sarLong switch context.positionStatus when "start" if (sarLong < instrument.price) #long context.positionStatus = "long" warn "LONG" break when "long" if (sarLong > instrument.price) && (context.buyPrice < instrument.price) #close long context.positionStatus = "close" break #### Trading debug "AMOUNT: #{@portfolio.positions[instrument.asset()].amount}" ######## LONG if context.positionStatus == "long" && (@portfolio.positions[instrument.base()].amount > 0) # open long position info "KAUFEN" trading.buy instrument context.buyPrice = instrument.price ######## CLOSE if context.positionStatus == "close" # close long position context.positionStatus = "start" if (@portfolio.positions[instrument.asset()].amount > 0) warn "VERKAUFEN" trading.sell instrument if context.verbose debug "######################################################## " onRestart: -> warn "RESTART DETECTED!!!" onStop: -> debug "######## BOT ENDE ########" debug "Start currency was__: #{storage.startCurrency} USD" debug "End currency is_____: #{context.currencyAvailable} USD" debug "Start asset was_____: #{storage.startAssets} #{storage.coin}" debug "End asset is________: #{context.assetsAvailable} #{storage.coin}" debug "Bot Gewinn__________: #{(((context.currencyAvailable + (context.assetsAvailable * context.currentPrice)) / storage.startCurrency - 1)*100).toFixed(2)}%" debug "B&H Gewinn__________: #{((context.currentPrice / storage.startPrice - 1)*100).toFixed(2)}%"
true
#### Copyright PI:NAME:<NAME>END_PI #### Collbot #### ToDos # - bei 'live' Bots verbose automatisch aktivieren # - beim start checken ob bereits eine Position offen ist und evtl. invested=true setzen # - Programmablauf / logging etc neu sortieren # - First Position Strategie? Warten bis zum nächsten Wechsel, oder direkt loslegen? # - Fees berechnen (0.2 % von komplettem Kauf- oder Verkaufswert) # Idee: Ultra Fast Bot 1Min-5Min Ticks... Pro Tag nur wenige aber dafür super safe trades "1% und gut" (bei margin sogar nur 0.4% nötig) -> 30% im Monat. #### START trading = require 'trading' # import core trading module talib = require 'talib' # import technical indicators library (https://cryptotrader.org/talib) _maximumExchangeFee = .20# params.add "Maximum exchange fee %", .25 _maximumOrderAmount = 1 #params.add "Maximum order amount", 1 _orderTimeout = 30 #params.add "Order timeout", 30 class functions #### TA-lib Indicatots @sar: (high, low, lag, accel, accelmax) -> results = talib.SAR high: high low: low startIdx: 0 endIdx: high.length - lag optInAcceleration: accel optInMaximum: accelmax _.last(results) #### Init init: -> context.verbose = true context.live = true context.sarAccel = 0.005 context.sarAccelmax = 0.5 context.sarAccelShort = 0.01 context.sarAccelmaxShort = 0.1 context.positionStatus = "start" context.buyPrice #### Tick execution handle: -> instrument = data.instruments[0] storage.coin ?= data.instruments[0].pair.substring(0, 3).toUpperCase() assetsAvailable = @portfolios[instrument.market].positions[instrument.asset()].amount context.assetsAvailable = assetsAvailable #current assets storage.startAssets ?= assetsAvailable #inital assets currencyAvailable = @portfolios[instrument.market].positions[instrument.curr()].amount context.currencyAvailable = currencyAvailable #current currency storage.startCurrency ?= currencyAvailable #inital currency context.currentPrice = instrument.price storage.startPrice ?= instrument.price #inital price maximumBuyAmount = (currencyAvailable/instrument.price) * (1 - (_maximumExchangeFee/100)) maximumSellAmount = (assetsAvailable * (1 - (_maximumExchangeFee/100))) diff = ((instrument.price / context.buyPrice - 1)*100) ##### Logging if context.verbose debug "Status____________: #{context.positionStatus}" debug "Balance ASSETS____: #{assetsAvailable} #{storage.coin}" debug "Balance CURRENCY__: #{currencyAvailable} USD" debug "Current PRICE_____: #{instrument.price} USD" debug "Current DIFF______: #{diff.toFixed(2)}%" debug "Bot Gewinn________: #{(((context.currencyAvailable + (context.assetsAvailable * context.currentPrice)) / storage.startCurrency - 1)*100).toFixed(2)}%" debug "B&H Gewinn________: #{((context.currentPrice / storage.startPrice - 1)*100).toFixed(2)}%" sarLong = functions.sar(instrument.high, instrument.low, 1,context.sarAccel, context.sarAccelmax) if (diff < -10) ||( diff > 5) && (@portfolio.positions[instrument.asset()].amount > 0) context.positionStatus = "close" warn "EMERGENCY EXIT!" plotMark "stop": 0 plot "sarLong": sarLong switch context.positionStatus when "start" if (sarLong < instrument.price) #long context.positionStatus = "long" warn "LONG" break when "long" if (sarLong > instrument.price) && (context.buyPrice < instrument.price) #close long context.positionStatus = "close" break #### Trading debug "AMOUNT: #{@portfolio.positions[instrument.asset()].amount}" ######## LONG if context.positionStatus == "long" && (@portfolio.positions[instrument.base()].amount > 0) # open long position info "KAUFEN" trading.buy instrument context.buyPrice = instrument.price ######## CLOSE if context.positionStatus == "close" # close long position context.positionStatus = "start" if (@portfolio.positions[instrument.asset()].amount > 0) warn "VERKAUFEN" trading.sell instrument if context.verbose debug "######################################################## " onRestart: -> warn "RESTART DETECTED!!!" onStop: -> debug "######## BOT ENDE ########" debug "Start currency was__: #{storage.startCurrency} USD" debug "End currency is_____: #{context.currencyAvailable} USD" debug "Start asset was_____: #{storage.startAssets} #{storage.coin}" debug "End asset is________: #{context.assetsAvailable} #{storage.coin}" debug "Bot Gewinn__________: #{(((context.currencyAvailable + (context.assetsAvailable * context.currentPrice)) / storage.startCurrency - 1)*100).toFixed(2)}%" debug "B&H Gewinn__________: #{((context.currentPrice / storage.startPrice - 1)*100).toFixed(2)}%"
[ { "context": "# s2.2.7.9, s2.2.7.10\n\nparser = (buffer, options) ->\n lengt", "end": 10, "score": 0.9772949814796448, "start": 3, "tag": "IP_ADDRESS", "value": "2.2.7.9" }, { "context": "# s2.2.7.9, s2.2.7.10\n\nparser = (buffer, options) ->\n length = buffer.", "end": 21, "score": 0.9954915046691895, "start": 13, "tag": "IP_ADDRESS", "value": "2.2.7.10" } ]
src/token/infoerror-token-parser.coffee
sgermain06/tedious-int64-native
1
# s2.2.7.9, s2.2.7.10 parser = (buffer, options) -> length = buffer.readUInt16LE() number = buffer.readUInt32LE() state = buffer.readUInt8() class_ = buffer.readUInt8() message = buffer.readUsVarchar() serverName = buffer.readBVarchar() procName = buffer.readBVarchar() if options.tdsVersion < '7_2' lineNumber = buffer.readUInt16LE() else lineNumber = buffer.readUInt32LE() token = number: number state: state class: class_ message: message serverName: serverName procName: procName lineNumber: lineNumber infoParser = (buffer, colMetadata, options) -> token = parser(buffer, options) token.name = 'INFO' token.event = 'infoMessage' token errorParser = (buffer, colMetadata, options) -> token = parser(buffer, options) token.name = 'ERROR' token.event = 'errorMessage' token exports.infoParser = infoParser exports.errorParser = errorParser
194282
# s172.16.17.32, s192.168.3.11 parser = (buffer, options) -> length = buffer.readUInt16LE() number = buffer.readUInt32LE() state = buffer.readUInt8() class_ = buffer.readUInt8() message = buffer.readUsVarchar() serverName = buffer.readBVarchar() procName = buffer.readBVarchar() if options.tdsVersion < '7_2' lineNumber = buffer.readUInt16LE() else lineNumber = buffer.readUInt32LE() token = number: number state: state class: class_ message: message serverName: serverName procName: procName lineNumber: lineNumber infoParser = (buffer, colMetadata, options) -> token = parser(buffer, options) token.name = 'INFO' token.event = 'infoMessage' token errorParser = (buffer, colMetadata, options) -> token = parser(buffer, options) token.name = 'ERROR' token.event = 'errorMessage' token exports.infoParser = infoParser exports.errorParser = errorParser
true
# sPI:IP_ADDRESS:172.16.17.32END_PI, sPI:IP_ADDRESS:192.168.3.11END_PI parser = (buffer, options) -> length = buffer.readUInt16LE() number = buffer.readUInt32LE() state = buffer.readUInt8() class_ = buffer.readUInt8() message = buffer.readUsVarchar() serverName = buffer.readBVarchar() procName = buffer.readBVarchar() if options.tdsVersion < '7_2' lineNumber = buffer.readUInt16LE() else lineNumber = buffer.readUInt32LE() token = number: number state: state class: class_ message: message serverName: serverName procName: procName lineNumber: lineNumber infoParser = (buffer, colMetadata, options) -> token = parser(buffer, options) token.name = 'INFO' token.event = 'infoMessage' token errorParser = (buffer, colMetadata, options) -> token = parser(buffer, options) token.name = 'ERROR' token.event = 'errorMessage' token exports.infoParser = infoParser exports.errorParser = errorParser
[ { "context": "\n If your data is mission critical, mail to info@piechopper.com.\n </p>\n \"\"\")\n\n addDefaultMembers = -> ", "end": 2061, "score": 0.9999272227287292, "start": 2042, "tag": "EMAIL", "value": "info@piechopper.com" } ]
app/coffee/controllers/appCtrl.coffee
mathewsk/cypress-example-piechopper
17
app.controller "AppCtrl", ($scope, $location, $http, $modal, $window, modelRepo, trace) => # from http://stackoverflow.com/a/2117523 uuid = -> "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace /[xy]/g, (c) -> r = Math.random() * 16 | 0 v = (if c is "x" then r else r & 0x3 | 0x8) v.toString 16 localStorage.userId = uuid() if not localStorage.userId $scope.userId = localStorage.userId # expose commonly used pieces to scope $scope.repo = repo = modelRepo.createRepo(modelDefs.all) $scope.model = model = -> repo.activeModel $scope.members = members = -> repo.activeModel.team.members $scope.criteria = (id) -> repo.activeModel.modelDef.criterias[id] $scope.memberColors = ["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c"] $scope.trace = trace $scope.moreResultsWanted = false # does user want more results to be shown? $scope.showMoreResults = (show) -> $scope.moreResultsWanted = show _linkToSnapshot = null $scope.linkToSnapshot = (val) -> _linkToSnapshot = val if val != undefined _linkToSnapshot $scope.showMessage = (title, desc, timeout) -> html = """ <div class="error-dlg"> <h2>#{title}</h2> <d>#{desc}</d> </div> """ dlg = $modal.open(template: html) if timeout $timeout((-> dlg.dismiss()), timeout) $scope.showTos = -> $scope.showMessage("Terms and Conditions", $('#tos').html()) $scope.trace.showTos() showUnknownProposalError = -> $scope.showMessage('Oops !', """ <p>The proposal you were looking for wasn't found.</p> <p> Please note that proposals older than a month are deleted. For more recent proposals, please check that your address is correct. </p> """) showInvalidProposalError = -> $scope.showMessage('Ooops !', """ <p> There was an error while loading the given address. Some parts of the proposal might not be correct! </p> <p> If your data is mission critical, mail to info@piechopper.com. </p> """) addDefaultMembers = -> repo.addMember() for [1..2] pathParts = $location.path().split('/') if pathParts.length == 3 and pathParts[1] == 'p' $http.get("/api/1/proposals/#{ pathParts[2] }"). success((data, status, headers, config) -> success = repo.deserialize(data.repo) if not success showInvalidProposalError() else $scope.$broadcast('modelLoaded') if data.userId and (data.userId == $scope.userId) $scope.trace.loadOwnProposal() else $scope.trace.loadPartnerProposal() ). error (data, status, headers, config) -> addDefaultMembers() showUnknownProposalError() else if pathParts.length >= 2 addDefaultMembers() showUnknownProposalError() else addDefaultMembers()
115295
app.controller "AppCtrl", ($scope, $location, $http, $modal, $window, modelRepo, trace) => # from http://stackoverflow.com/a/2117523 uuid = -> "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace /[xy]/g, (c) -> r = Math.random() * 16 | 0 v = (if c is "x" then r else r & 0x3 | 0x8) v.toString 16 localStorage.userId = uuid() if not localStorage.userId $scope.userId = localStorage.userId # expose commonly used pieces to scope $scope.repo = repo = modelRepo.createRepo(modelDefs.all) $scope.model = model = -> repo.activeModel $scope.members = members = -> repo.activeModel.team.members $scope.criteria = (id) -> repo.activeModel.modelDef.criterias[id] $scope.memberColors = ["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c"] $scope.trace = trace $scope.moreResultsWanted = false # does user want more results to be shown? $scope.showMoreResults = (show) -> $scope.moreResultsWanted = show _linkToSnapshot = null $scope.linkToSnapshot = (val) -> _linkToSnapshot = val if val != undefined _linkToSnapshot $scope.showMessage = (title, desc, timeout) -> html = """ <div class="error-dlg"> <h2>#{title}</h2> <d>#{desc}</d> </div> """ dlg = $modal.open(template: html) if timeout $timeout((-> dlg.dismiss()), timeout) $scope.showTos = -> $scope.showMessage("Terms and Conditions", $('#tos').html()) $scope.trace.showTos() showUnknownProposalError = -> $scope.showMessage('Oops !', """ <p>The proposal you were looking for wasn't found.</p> <p> Please note that proposals older than a month are deleted. For more recent proposals, please check that your address is correct. </p> """) showInvalidProposalError = -> $scope.showMessage('Ooops !', """ <p> There was an error while loading the given address. Some parts of the proposal might not be correct! </p> <p> If your data is mission critical, mail to <EMAIL>. </p> """) addDefaultMembers = -> repo.addMember() for [1..2] pathParts = $location.path().split('/') if pathParts.length == 3 and pathParts[1] == 'p' $http.get("/api/1/proposals/#{ pathParts[2] }"). success((data, status, headers, config) -> success = repo.deserialize(data.repo) if not success showInvalidProposalError() else $scope.$broadcast('modelLoaded') if data.userId and (data.userId == $scope.userId) $scope.trace.loadOwnProposal() else $scope.trace.loadPartnerProposal() ). error (data, status, headers, config) -> addDefaultMembers() showUnknownProposalError() else if pathParts.length >= 2 addDefaultMembers() showUnknownProposalError() else addDefaultMembers()
true
app.controller "AppCtrl", ($scope, $location, $http, $modal, $window, modelRepo, trace) => # from http://stackoverflow.com/a/2117523 uuid = -> "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace /[xy]/g, (c) -> r = Math.random() * 16 | 0 v = (if c is "x" then r else r & 0x3 | 0x8) v.toString 16 localStorage.userId = uuid() if not localStorage.userId $scope.userId = localStorage.userId # expose commonly used pieces to scope $scope.repo = repo = modelRepo.createRepo(modelDefs.all) $scope.model = model = -> repo.activeModel $scope.members = members = -> repo.activeModel.team.members $scope.criteria = (id) -> repo.activeModel.modelDef.criterias[id] $scope.memberColors = ["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c"] $scope.trace = trace $scope.moreResultsWanted = false # does user want more results to be shown? $scope.showMoreResults = (show) -> $scope.moreResultsWanted = show _linkToSnapshot = null $scope.linkToSnapshot = (val) -> _linkToSnapshot = val if val != undefined _linkToSnapshot $scope.showMessage = (title, desc, timeout) -> html = """ <div class="error-dlg"> <h2>#{title}</h2> <d>#{desc}</d> </div> """ dlg = $modal.open(template: html) if timeout $timeout((-> dlg.dismiss()), timeout) $scope.showTos = -> $scope.showMessage("Terms and Conditions", $('#tos').html()) $scope.trace.showTos() showUnknownProposalError = -> $scope.showMessage('Oops !', """ <p>The proposal you were looking for wasn't found.</p> <p> Please note that proposals older than a month are deleted. For more recent proposals, please check that your address is correct. </p> """) showInvalidProposalError = -> $scope.showMessage('Ooops !', """ <p> There was an error while loading the given address. Some parts of the proposal might not be correct! </p> <p> If your data is mission critical, mail to PI:EMAIL:<EMAIL>END_PI. </p> """) addDefaultMembers = -> repo.addMember() for [1..2] pathParts = $location.path().split('/') if pathParts.length == 3 and pathParts[1] == 'p' $http.get("/api/1/proposals/#{ pathParts[2] }"). success((data, status, headers, config) -> success = repo.deserialize(data.repo) if not success showInvalidProposalError() else $scope.$broadcast('modelLoaded') if data.userId and (data.userId == $scope.userId) $scope.trace.loadOwnProposal() else $scope.trace.loadPartnerProposal() ). error (data, status, headers, config) -> addDefaultMembers() showUnknownProposalError() else if pathParts.length >= 2 addDefaultMembers() showUnknownProposalError() else addDefaultMembers()
[ { "context": "###\n backbone-rest.js 0.5.3\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-rest\n Lic", "end": 58, "score": 0.9993582963943481, "start": 50, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-rest\n License: MIT (http://www.opensour", "end": 88, "score": 0.9997077584266663, "start": 80, "tag": "USERNAME", "value": "vidigami" } ]
src/lib/json_controller.coffee
founderlab/fl-backbone-rest
0
### backbone-rest.js 0.5.3 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-rest License: MIT (http://www.opensource.org/licenses/mit-license.php) ### _ = require 'underscore' BackboneEvents = (require 'backbone').Events module.exports = class JSONController constructor: (app, options={}) -> @configure(options) @headers or= {'Cache-Control': 'no-cache', 'Content-Type': 'application/json'} @logger or= console configure: (options={}) -> _.extend(@, options) sendStatus: (res, status, message) -> res.status(status); if message then res.json({message}) else res.json({}) sendError: (res, err) -> req = res.req @constructor.trigger('error', {req: req, res: res, err: err}) @logger.error("Error 500 from #{req.method} #{req.url}: #{err?.stack or err}") res.status(500); res.json({error: err.toString()}) wrap: (fn) => stack = [] if _.isArray(@auth) then stack = @auth.slice(0) # copy so middleware can attach to an instance else if _.isFunction(@auth) then stack.push(@auth) else if _.isObject(@auth) then stack.push(@_dynamicAuth) stack.push(@_setHeaders) stack.push (req, res, next) => (return @sendStatus(res, 405) if @_reqToCRUD(req) in @blocked) if @blocked try fn.call(@, req, res, next) catch err then @sendError(res, err) return stack _call: @::wrap # TODO: add deprecation warning requestValue: (req, key) -> return if _.isFunction(req[key]) then req[key]() else req[key] ################################ # Private ################################ _setHeaders: (req, res, next) => res.setHeader(key, value) for key, value of @headers next() _reqToCRUD: (req) => req_path = @requestValue(req, 'path') if req_path is @route switch req.method when 'GET' then return 'index' when 'POST' then return 'create' when 'DELETE' then return 'destroyByQuery' when 'HEAD' then return 'headByQuery' else if @requestId(req) and req_path is "#{@route}/#{@requestId(req)}" switch req.method when 'GET' then return 'show' when 'PUT' then return 'update' when 'DELETE' then return 'destroy' when 'HEAD' then return 'head' _dynamicAuth: (req, res, next) => if @auth.hasOwnProperty(crud = @_reqToCRUD(req)) then auth = @auth[crud] else auth = @auth.default return next() unless auth return auth(req, res, next) unless _.isArray(auth) index = -1 exec = -> if (++index >= auth.length) then next() else auth[index](req, res, exec) exec() _.extend(JSONController, BackboneEvents)
200956
### backbone-rest.js 0.5.3 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-rest License: MIT (http://www.opensource.org/licenses/mit-license.php) ### _ = require 'underscore' BackboneEvents = (require 'backbone').Events module.exports = class JSONController constructor: (app, options={}) -> @configure(options) @headers or= {'Cache-Control': 'no-cache', 'Content-Type': 'application/json'} @logger or= console configure: (options={}) -> _.extend(@, options) sendStatus: (res, status, message) -> res.status(status); if message then res.json({message}) else res.json({}) sendError: (res, err) -> req = res.req @constructor.trigger('error', {req: req, res: res, err: err}) @logger.error("Error 500 from #{req.method} #{req.url}: #{err?.stack or err}") res.status(500); res.json({error: err.toString()}) wrap: (fn) => stack = [] if _.isArray(@auth) then stack = @auth.slice(0) # copy so middleware can attach to an instance else if _.isFunction(@auth) then stack.push(@auth) else if _.isObject(@auth) then stack.push(@_dynamicAuth) stack.push(@_setHeaders) stack.push (req, res, next) => (return @sendStatus(res, 405) if @_reqToCRUD(req) in @blocked) if @blocked try fn.call(@, req, res, next) catch err then @sendError(res, err) return stack _call: @::wrap # TODO: add deprecation warning requestValue: (req, key) -> return if _.isFunction(req[key]) then req[key]() else req[key] ################################ # Private ################################ _setHeaders: (req, res, next) => res.setHeader(key, value) for key, value of @headers next() _reqToCRUD: (req) => req_path = @requestValue(req, 'path') if req_path is @route switch req.method when 'GET' then return 'index' when 'POST' then return 'create' when 'DELETE' then return 'destroyByQuery' when 'HEAD' then return 'headByQuery' else if @requestId(req) and req_path is "#{@route}/#{@requestId(req)}" switch req.method when 'GET' then return 'show' when 'PUT' then return 'update' when 'DELETE' then return 'destroy' when 'HEAD' then return 'head' _dynamicAuth: (req, res, next) => if @auth.hasOwnProperty(crud = @_reqToCRUD(req)) then auth = @auth[crud] else auth = @auth.default return next() unless auth return auth(req, res, next) unless _.isArray(auth) index = -1 exec = -> if (++index >= auth.length) then next() else auth[index](req, res, exec) exec() _.extend(JSONController, BackboneEvents)
true
### backbone-rest.js 0.5.3 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-rest License: MIT (http://www.opensource.org/licenses/mit-license.php) ### _ = require 'underscore' BackboneEvents = (require 'backbone').Events module.exports = class JSONController constructor: (app, options={}) -> @configure(options) @headers or= {'Cache-Control': 'no-cache', 'Content-Type': 'application/json'} @logger or= console configure: (options={}) -> _.extend(@, options) sendStatus: (res, status, message) -> res.status(status); if message then res.json({message}) else res.json({}) sendError: (res, err) -> req = res.req @constructor.trigger('error', {req: req, res: res, err: err}) @logger.error("Error 500 from #{req.method} #{req.url}: #{err?.stack or err}") res.status(500); res.json({error: err.toString()}) wrap: (fn) => stack = [] if _.isArray(@auth) then stack = @auth.slice(0) # copy so middleware can attach to an instance else if _.isFunction(@auth) then stack.push(@auth) else if _.isObject(@auth) then stack.push(@_dynamicAuth) stack.push(@_setHeaders) stack.push (req, res, next) => (return @sendStatus(res, 405) if @_reqToCRUD(req) in @blocked) if @blocked try fn.call(@, req, res, next) catch err then @sendError(res, err) return stack _call: @::wrap # TODO: add deprecation warning requestValue: (req, key) -> return if _.isFunction(req[key]) then req[key]() else req[key] ################################ # Private ################################ _setHeaders: (req, res, next) => res.setHeader(key, value) for key, value of @headers next() _reqToCRUD: (req) => req_path = @requestValue(req, 'path') if req_path is @route switch req.method when 'GET' then return 'index' when 'POST' then return 'create' when 'DELETE' then return 'destroyByQuery' when 'HEAD' then return 'headByQuery' else if @requestId(req) and req_path is "#{@route}/#{@requestId(req)}" switch req.method when 'GET' then return 'show' when 'PUT' then return 'update' when 'DELETE' then return 'destroy' when 'HEAD' then return 'head' _dynamicAuth: (req, res, next) => if @auth.hasOwnProperty(crud = @_reqToCRUD(req)) then auth = @auth[crud] else auth = @auth.default return next() unless auth return auth(req, res, next) unless _.isArray(auth) index = -1 exec = -> if (++index >= auth.length) then next() else auth[index](req, res, exec) exec() _.extend(JSONController, BackboneEvents)
[ { "context": " @getGithub = @github\n .get '/users/sqrtofsaturn/followers'\n .query access_token: 'gith", "end": 2468, "score": 0.5892256498336792, "start": 2459, "tag": "USERNAME", "value": "tofsaturn" }, { "context": "en'\n .reply 200,\n login: 'travist'\n id: 130052\n avatar_ur", "end": 2593, "score": 0.999728262424469, "start": 2586, "tag": "USERNAME", "value": "travist" }, { "context": "Port}\"\n auth:\n username: 'flow-uuid'\n password: 'flow-token'\n ", "end": 2855, "score": 0.9994986653327942, "start": 2846, "tag": "USERNAME", "value": "flow-uuid" }, { "context": " username: 'flow-uuid'\n password: 'flow-token'\n json:\n channelid: '532a", "end": 2892, "score": 0.9993059635162354, "start": 2882, "tag": "PASSWORD", "value": "flow-token" }, { "context": " urlParams:\n ':username': 'sqrtofsaturn'\n queryParams: {}\n body", "end": 3220, "score": 0.9997072219848633, "start": 3208, "tag": "USERNAME", "value": "sqrtofsaturn" }, { "context": " expect(@body).to.deep.equal\n login: 'travist'\n id: 130052\n avatar_url: '", "end": 3786, "score": 0.9997053742408752, "start": 3779, "tag": "USERNAME", "value": "travist" } ]
test/integration/channel-proxy-github-make-request-spec.coffee
octoblu/channel-proxy-service
0
http = require 'http' request = require 'request' mongojs = require 'mongojs' {ObjectId} = require 'mongojs' shmock = require '@octoblu/shmock' Server = require '../../src/server' ChannelConfig = require '../../src/models/channel-config' textCrypt = require '../../src/models/text-crypt' describe 'Github Make Request', -> beforeEach -> @mongoDbUri = 'octoblu-test-database' @database = mongojs @mongoDbUri, ['users', 'flows'] beforeEach (done) -> @database.users.remove => done() beforeEach (done) -> @database.flows.remove => done() beforeEach (done) -> @meshblu = shmock 0xd00d @github = shmock 0xbabe serverOptions = port: undefined, disableLogging: true meshbluConfig = server: 'localhost' port: 0xd00d channelConfig = new ChannelConfig {} channelConfig.fetch = sinon.stub().yields null channelConfig._channels = [ require('../data/github-channel.json'), require('../data/weather-channel.json') ] @server = new Server serverOptions, {meshbluConfig, @mongoDbUri, channelConfig} @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @meshblu.close done afterEach (done) -> @github.close done describe 'when a flows is stored in mongo', -> beforeEach (done) -> flow = flowId: 'flow-uuid' resource: owner: uuid: 'user-uuid' @database.flows.insert flow, done describe 'when a user is stored in mongo', -> beforeEach (done) -> user = resource: uuid: 'user-uuid' api: [ authtype: "oauth", token_crypt: textCrypt.encrypt 'github-auth-access-token' channelid: ObjectId("532a258a50411e5802cb8053"), _id: ObjectId("56a1254b0c6266010001875e"), type: "channel:github", uuid: "channel-github-uuid" ] @database.users.insert user, done describe 'when the service succeeds', -> beforeEach (done) -> flowAuth = new Buffer('flow-uuid:flow-token').toString 'base64' @authDevice = @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{flowAuth}" .reply 200, uuid: 'flow-uuid', token: 'flow-token' @getGithub = @github .get '/users/sqrtofsaturn/followers' .query access_token: 'github-auth-access-token' .reply 200, login: 'travist' id: 130052 avatar_url: 'https://avatars.githubusercontent.com/u/130052?v=3' options = uri: '/request' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'flow-uuid' password: 'flow-token' json: channelid: '532a258a50411e5802cb8053' channelActivationId: '56a1254b0c6266010001875e' uuid: 'e56842b0-5e2e-11e5-8abf-b33a470ad64b' type: 'channel:github' headerParams: {} urlParams: ':username': 'sqrtofsaturn' queryParams: {} bodyParams: {} url: "http://localhost:#{0xbabe}/users/:username/followers", method: 'GET' request.post options, (error, @response, @body) => done error it 'should auth handler', -> @authDevice.done() it 'should get the github', -> @getGithub.done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200 it 'should return a body', -> expect(@body).to.deep.equal login: 'travist' id: 130052 avatar_url: 'https://avatars.githubusercontent.com/u/130052?v=3'
149289
http = require 'http' request = require 'request' mongojs = require 'mongojs' {ObjectId} = require 'mongojs' shmock = require '@octoblu/shmock' Server = require '../../src/server' ChannelConfig = require '../../src/models/channel-config' textCrypt = require '../../src/models/text-crypt' describe 'Github Make Request', -> beforeEach -> @mongoDbUri = 'octoblu-test-database' @database = mongojs @mongoDbUri, ['users', 'flows'] beforeEach (done) -> @database.users.remove => done() beforeEach (done) -> @database.flows.remove => done() beforeEach (done) -> @meshblu = shmock 0xd00d @github = shmock 0xbabe serverOptions = port: undefined, disableLogging: true meshbluConfig = server: 'localhost' port: 0xd00d channelConfig = new ChannelConfig {} channelConfig.fetch = sinon.stub().yields null channelConfig._channels = [ require('../data/github-channel.json'), require('../data/weather-channel.json') ] @server = new Server serverOptions, {meshbluConfig, @mongoDbUri, channelConfig} @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @meshblu.close done afterEach (done) -> @github.close done describe 'when a flows is stored in mongo', -> beforeEach (done) -> flow = flowId: 'flow-uuid' resource: owner: uuid: 'user-uuid' @database.flows.insert flow, done describe 'when a user is stored in mongo', -> beforeEach (done) -> user = resource: uuid: 'user-uuid' api: [ authtype: "oauth", token_crypt: textCrypt.encrypt 'github-auth-access-token' channelid: ObjectId("532a258a50411e5802cb8053"), _id: ObjectId("56a1254b0c6266010001875e"), type: "channel:github", uuid: "channel-github-uuid" ] @database.users.insert user, done describe 'when the service succeeds', -> beforeEach (done) -> flowAuth = new Buffer('flow-uuid:flow-token').toString 'base64' @authDevice = @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{flowAuth}" .reply 200, uuid: 'flow-uuid', token: 'flow-token' @getGithub = @github .get '/users/sqrtofsaturn/followers' .query access_token: 'github-auth-access-token' .reply 200, login: 'travist' id: 130052 avatar_url: 'https://avatars.githubusercontent.com/u/130052?v=3' options = uri: '/request' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'flow-uuid' password: '<PASSWORD>' json: channelid: '532a258a50411e5802cb8053' channelActivationId: '56a1254b0c6266010001875e' uuid: 'e56842b0-5e2e-11e5-8abf-b33a470ad64b' type: 'channel:github' headerParams: {} urlParams: ':username': 'sqrtofsaturn' queryParams: {} bodyParams: {} url: "http://localhost:#{0xbabe}/users/:username/followers", method: 'GET' request.post options, (error, @response, @body) => done error it 'should auth handler', -> @authDevice.done() it 'should get the github', -> @getGithub.done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200 it 'should return a body', -> expect(@body).to.deep.equal login: 'travist' id: 130052 avatar_url: 'https://avatars.githubusercontent.com/u/130052?v=3'
true
http = require 'http' request = require 'request' mongojs = require 'mongojs' {ObjectId} = require 'mongojs' shmock = require '@octoblu/shmock' Server = require '../../src/server' ChannelConfig = require '../../src/models/channel-config' textCrypt = require '../../src/models/text-crypt' describe 'Github Make Request', -> beforeEach -> @mongoDbUri = 'octoblu-test-database' @database = mongojs @mongoDbUri, ['users', 'flows'] beforeEach (done) -> @database.users.remove => done() beforeEach (done) -> @database.flows.remove => done() beforeEach (done) -> @meshblu = shmock 0xd00d @github = shmock 0xbabe serverOptions = port: undefined, disableLogging: true meshbluConfig = server: 'localhost' port: 0xd00d channelConfig = new ChannelConfig {} channelConfig.fetch = sinon.stub().yields null channelConfig._channels = [ require('../data/github-channel.json'), require('../data/weather-channel.json') ] @server = new Server serverOptions, {meshbluConfig, @mongoDbUri, channelConfig} @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @meshblu.close done afterEach (done) -> @github.close done describe 'when a flows is stored in mongo', -> beforeEach (done) -> flow = flowId: 'flow-uuid' resource: owner: uuid: 'user-uuid' @database.flows.insert flow, done describe 'when a user is stored in mongo', -> beforeEach (done) -> user = resource: uuid: 'user-uuid' api: [ authtype: "oauth", token_crypt: textCrypt.encrypt 'github-auth-access-token' channelid: ObjectId("532a258a50411e5802cb8053"), _id: ObjectId("56a1254b0c6266010001875e"), type: "channel:github", uuid: "channel-github-uuid" ] @database.users.insert user, done describe 'when the service succeeds', -> beforeEach (done) -> flowAuth = new Buffer('flow-uuid:flow-token').toString 'base64' @authDevice = @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{flowAuth}" .reply 200, uuid: 'flow-uuid', token: 'flow-token' @getGithub = @github .get '/users/sqrtofsaturn/followers' .query access_token: 'github-auth-access-token' .reply 200, login: 'travist' id: 130052 avatar_url: 'https://avatars.githubusercontent.com/u/130052?v=3' options = uri: '/request' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'flow-uuid' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: channelid: '532a258a50411e5802cb8053' channelActivationId: '56a1254b0c6266010001875e' uuid: 'e56842b0-5e2e-11e5-8abf-b33a470ad64b' type: 'channel:github' headerParams: {} urlParams: ':username': 'sqrtofsaturn' queryParams: {} bodyParams: {} url: "http://localhost:#{0xbabe}/users/:username/followers", method: 'GET' request.post options, (error, @response, @body) => done error it 'should auth handler', -> @authDevice.done() it 'should get the github', -> @getGithub.done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200 it 'should return a body', -> expect(@body).to.deep.equal login: 'travist' id: 130052 avatar_url: 'https://avatars.githubusercontent.com/u/130052?v=3'
[ { "context": "'three', text: '', filterText: 'x'}\n {name: 'four', text: '', filterText: 'z'}\n ]\n list.setIt", "end": 1851, "score": 0.8539687991142273, "start": 1847, "tag": "NAME", "value": "four" }, { "context": "list.setItems(items)\n\n items = [\n {name: 'one', text: '', filterText: 'x'},\n {name: 'two',", "end": 1944, "score": 0.8425489664077759, "start": 1941, "tag": "NAME", "value": "one" }, { "context": " 'one', text: '', filterText: 'x'},\n {name: 'two', text: '', filterText: 'y'}\n {name: 'three'", "end": 1992, "score": 0.8338369727134705, "start": 1989, "tag": "NAME", "value": "two" }, { "context": ": 'two', text: '', filterText: 'y'}\n {name: 'three', text: '', filterText: 'x'}\n {name: 'four',", "end": 2041, "score": 0.897617757320404, "start": 2036, "tag": "NAME", "value": "three" }, { "context": "'three', text: '', filterText: 'x'}\n {name: 'four', text: '', filterText: 'z'}\n ]\n list.setIt", "end": 2089, "score": 0.8462212681770325, "start": 2085, "tag": "NAME", "value": "four" } ]
spec/list-view-spec.coffee
Aerijo/settings-view
316
List = require '../lib/list' ListView = require '../lib/list-view' describe 'ListView', -> [list, view, container] = [] beforeEach -> list = new List('name') container = document.createElement('div') view = new ListView list, container, (item) -> element = document.createElement('div') element.classList.add(item.name) element.textContent = "#{item.name}|#{item.text}" {element, destroy: -> element.remove()} it 'updates the list when the items are changed', -> expect(container.children.length).toBe 0 items = [{name: 'one', text: 'a'}, {name: 'two', text: 'b'}] list.setItems(items) expect(container.children.length).toBe 2 expect(container.querySelector('.one').textContent).toBe 'one|a' expect(container.querySelector('.two').textContent).toBe 'two|b' items = [{name: 'three', text: 'c'}, {name: 'two', text: 'b'}] list.setItems(items) expect(container.children.length).toBe 2 expect(container.querySelector('.one')).not.toExist() expect(container.querySelector('.two').textContent).toBe 'two|b' expect(container.querySelector('.three').textContent).toBe 'three|c' it 'filters views', -> items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: 'four', text: '', filterText: 'z'} ] list.setItems(items) views = view.filterViews (item) -> item.filterText is 'x' expect(views).toHaveLength 2 expect(views[0].element.textContent).toBe 'one|' expect(views[1].element.textContent).toBe 'three|' it 'filters views after an update', -> items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: 'four', text: '', filterText: 'z'} ] list.setItems(items) items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: 'four', text: '', filterText: 'z'} ] list.setItems(items) views = view.filterViews (item) -> item.filterText is 'x' expect(views).toHaveLength 2 expect(views[0].element.textContent).toBe 'one|' expect(views[1].element.textContent).toBe 'three|'
91475
List = require '../lib/list' ListView = require '../lib/list-view' describe 'ListView', -> [list, view, container] = [] beforeEach -> list = new List('name') container = document.createElement('div') view = new ListView list, container, (item) -> element = document.createElement('div') element.classList.add(item.name) element.textContent = "#{item.name}|#{item.text}" {element, destroy: -> element.remove()} it 'updates the list when the items are changed', -> expect(container.children.length).toBe 0 items = [{name: 'one', text: 'a'}, {name: 'two', text: 'b'}] list.setItems(items) expect(container.children.length).toBe 2 expect(container.querySelector('.one').textContent).toBe 'one|a' expect(container.querySelector('.two').textContent).toBe 'two|b' items = [{name: 'three', text: 'c'}, {name: 'two', text: 'b'}] list.setItems(items) expect(container.children.length).toBe 2 expect(container.querySelector('.one')).not.toExist() expect(container.querySelector('.two').textContent).toBe 'two|b' expect(container.querySelector('.three').textContent).toBe 'three|c' it 'filters views', -> items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: 'four', text: '', filterText: 'z'} ] list.setItems(items) views = view.filterViews (item) -> item.filterText is 'x' expect(views).toHaveLength 2 expect(views[0].element.textContent).toBe 'one|' expect(views[1].element.textContent).toBe 'three|' it 'filters views after an update', -> items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: '<NAME>', text: '', filterText: 'z'} ] list.setItems(items) items = [ {name: '<NAME>', text: '', filterText: 'x'}, {name: '<NAME>', text: '', filterText: 'y'} {name: '<NAME>', text: '', filterText: 'x'} {name: '<NAME>', text: '', filterText: 'z'} ] list.setItems(items) views = view.filterViews (item) -> item.filterText is 'x' expect(views).toHaveLength 2 expect(views[0].element.textContent).toBe 'one|' expect(views[1].element.textContent).toBe 'three|'
true
List = require '../lib/list' ListView = require '../lib/list-view' describe 'ListView', -> [list, view, container] = [] beforeEach -> list = new List('name') container = document.createElement('div') view = new ListView list, container, (item) -> element = document.createElement('div') element.classList.add(item.name) element.textContent = "#{item.name}|#{item.text}" {element, destroy: -> element.remove()} it 'updates the list when the items are changed', -> expect(container.children.length).toBe 0 items = [{name: 'one', text: 'a'}, {name: 'two', text: 'b'}] list.setItems(items) expect(container.children.length).toBe 2 expect(container.querySelector('.one').textContent).toBe 'one|a' expect(container.querySelector('.two').textContent).toBe 'two|b' items = [{name: 'three', text: 'c'}, {name: 'two', text: 'b'}] list.setItems(items) expect(container.children.length).toBe 2 expect(container.querySelector('.one')).not.toExist() expect(container.querySelector('.two').textContent).toBe 'two|b' expect(container.querySelector('.three').textContent).toBe 'three|c' it 'filters views', -> items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: 'four', text: '', filterText: 'z'} ] list.setItems(items) views = view.filterViews (item) -> item.filterText is 'x' expect(views).toHaveLength 2 expect(views[0].element.textContent).toBe 'one|' expect(views[1].element.textContent).toBe 'three|' it 'filters views after an update', -> items = [ {name: 'one', text: '', filterText: 'x'}, {name: 'two', text: '', filterText: 'y'} {name: 'three', text: '', filterText: 'x'} {name: 'PI:NAME:<NAME>END_PI', text: '', filterText: 'z'} ] list.setItems(items) items = [ {name: 'PI:NAME:<NAME>END_PI', text: '', filterText: 'x'}, {name: 'PI:NAME:<NAME>END_PI', text: '', filterText: 'y'} {name: 'PI:NAME:<NAME>END_PI', text: '', filterText: 'x'} {name: 'PI:NAME:<NAME>END_PI', text: '', filterText: 'z'} ] list.setItems(items) views = view.filterViews (item) -> item.filterText is 'x' expect(views).toHaveLength 2 expect(views[0].element.textContent).toBe 'one|' expect(views[1].element.textContent).toBe 'three|'
[ { "context": " e.g. http://elastic.search.com:80\n#\n# Author:\n# HenryCook <henry@havingatinker.uk>\n\n{spawn, exec} = requir", "end": 373, "score": 0.9988150596618652, "start": 364, "tag": "NAME", "value": "HenryCook" }, { "context": "/elastic.search.com:80\n#\n# Author:\n# HenryCook <henry@havingatinker.uk>\n\n{spawn, exec} = require 'child_process'\nmodule", "end": 397, "score": 0.9999278783798218, "start": 375, "tag": "EMAIL", "value": "henry@havingatinker.uk" } ]
scripts/elasticsearch.coffee
HenryCook/hubot-scripts
0
# Description: # Interacts with Elasticsearch # # Commands: # hubot elasticsearch list indices - Lists all indices in ElasticSearch Cluster. # hubot elasticsearch remove index <host> - Removes index from Elasticsearch Cluster. # # Configuration: # ELASTICSEARCH_ENDPOINT - The endpoint for Salt's REST API e.g. http://elastic.search.com:80 # # Author: # HenryCook <henry@havingatinker.uk> {spawn, exec} = require 'child_process' module.exports = (robot) -> robot.respond /elasticsearch list indices/i, (msg) -> c = "/opt/hubot/bin/elasticsearch/es_tool.py --list-all-indices" exec c, (err, stdout, stderr) -> msg.send stdout msg.send stderr msg.send err robot.respond /elasticsearch remove index ([^ ]+)\s*(\w*)/i, (msg) -> c = "/opt/hubot/bin/elasticsearch/es_tool.py --delete-index "+ msg.match[1] exec c, (err, stdout, stderr) -> msg.send stdout msg.send stderr msg.send err
65387
# Description: # Interacts with Elasticsearch # # Commands: # hubot elasticsearch list indices - Lists all indices in ElasticSearch Cluster. # hubot elasticsearch remove index <host> - Removes index from Elasticsearch Cluster. # # Configuration: # ELASTICSEARCH_ENDPOINT - The endpoint for Salt's REST API e.g. http://elastic.search.com:80 # # Author: # <NAME> <<EMAIL>> {spawn, exec} = require 'child_process' module.exports = (robot) -> robot.respond /elasticsearch list indices/i, (msg) -> c = "/opt/hubot/bin/elasticsearch/es_tool.py --list-all-indices" exec c, (err, stdout, stderr) -> msg.send stdout msg.send stderr msg.send err robot.respond /elasticsearch remove index ([^ ]+)\s*(\w*)/i, (msg) -> c = "/opt/hubot/bin/elasticsearch/es_tool.py --delete-index "+ msg.match[1] exec c, (err, stdout, stderr) -> msg.send stdout msg.send stderr msg.send err
true
# Description: # Interacts with Elasticsearch # # Commands: # hubot elasticsearch list indices - Lists all indices in ElasticSearch Cluster. # hubot elasticsearch remove index <host> - Removes index from Elasticsearch Cluster. # # Configuration: # ELASTICSEARCH_ENDPOINT - The endpoint for Salt's REST API e.g. http://elastic.search.com:80 # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> {spawn, exec} = require 'child_process' module.exports = (robot) -> robot.respond /elasticsearch list indices/i, (msg) -> c = "/opt/hubot/bin/elasticsearch/es_tool.py --list-all-indices" exec c, (err, stdout, stderr) -> msg.send stdout msg.send stderr msg.send err robot.respond /elasticsearch remove index ([^ ]+)\s*(\w*)/i, (msg) -> c = "/opt/hubot/bin/elasticsearch/es_tool.py --delete-index "+ msg.match[1] exec c, (err, stdout, stderr) -> msg.send stdout msg.send stderr msg.send err
[ { "context": "\nDisassembler = require 'disasm'\n\nEXAMPLE_CODE = \"\nIyMjIE11bHRpcGxpY2F0aW9uIG9mIHR3byBudW1iZXJzCiMgVmFsdWVzIGFyZSBsb2FkZWQgZnJv\nbSBSYW0sCiMgYXQgYWRkcmVzc2VzIDMgYW5kIDQuCiMgUmVzdWx0IGlzIHdyaXR0ZW4gaW50byBh\nZGRyZXNzIDkKIyAKIyBUbyBzZXQgaW5pdGlhbCB2YWx1ZXMgZm9yIFJhbS9SZWdpc3RlcnMKIyBk\nb3VibGUgY2xpY2sgYW55IGxpbmUgKG9uIHRoZSBsZWZ0IC0tPikKIyBhbmQgY29uZmlybSB3aXRo\nICplbnRlciogb3Igd2l0aCBjbGlja2luZwojIG5leHQgdG8gdGhlIGlucHV0IGZpZWxkLgojCiMg\nRnVuIHN0YXJ0cyBoZXJlOgpSNzwtbHNoKDErMSkgIyBsZWZ0c2hpZnQsIGFmdGVyIGFkZGl0aW9u\nClI3PC1SNytSNwpSODwtMApSNjwtKDErMSkgIyBvcHRpb25hbCBwYXJlbnMKUjY8LVI2KzEKTUFS\nPC1SNjtyZCAjIFJlYWQgZnJvbSBSYW0gKGFkZHI9MykKcmQgIyBSYW0gbmVlZHMgdHdvIGN5Y2xl\ncyB0byBmZXRjaCBkYXRhClI5PC1NQlIgIyB3cml0ZSB0aGUgZmV0Y2hlZCBkYXRhIGludG8gcmVn\naXN0ZXIgUjkKUjY8LVI2KzEKTUFSPC1SNjtyZCAjIFJlYWQgZnJvbSBSYW0gKGFkZHI9NCkKcmQK\nUjEwPC1NQlIgIyB3cml0ZSB0aGUgZmV0Y2hlZCBkYXRhIGludG8gcmVnaXN0ZXIgUjEwCiMgSGVy\nZSBiYXNpY2FsbHkgc3RhcnRzIHRoZSBtdWx0aXBsaWNhdGlvbgojIGFuZCBlbmRzIGF0IGxhYmVs\nIDplbmRsb29wClI5PC1sc2goUjkrUjkpClI5PC1sc2goUjkrUjkpClI5PC1sc2goUjkrUjkpClI5\nPC1sc2goUjkrUjkpCiMgOmxhYmVsIGRlY2xhcmVzIGEgbGFiZWwsCiMgeW91IGNhbiBqdW1wIHRv\nIGl0IHdpdGggZ290byAubGFiZWwKKFI3KTsgaWYgWiBnb3RvIC5lbmRsb29wIDpzdGFydGxvb3AK\nUjg8LWxzaChSOCkKKH5SOSk7IGlmIE4gZ290byAuc2tpcApSODwtUjgrUjEwClI5PC1sc2goUjkp\nIDpza2lwClI3PC1SNysoLTEpCmdvdG8gLnN0YXJ0bG9vcApSNjwtUjYrUjYgOmVuZGxvb3AKUjY8\nLVI2KzEKTUFSPC1SNgpNQlI8LVI4O3dyICMgV3JpdGUgcmVzdWx0IHRvIFJhbSAoYWRkcj05KQp3\nciAjIFJhbSBuZWVkcyBhbHNvIHR3byBjeWNsZXMgdG8gd3JpdGUgZGF0YQ==\"\n\nDISASM_HTML = '<div class=\"toolbar\" class=\"conta", "end": 1523, "score": 0.9997174739837646, "start": 76, "tag": "KEY", "value": "IyMjIE11bHRpcGxpY2F0aW9uIG9mIHR3byBudW1iZXJzCiMgVmFsdWVzIGFyZSBsb2FkZWQgZnJv\nbSBSYW0sCiMgYXQgYWRkcmVzc2VzIDMgYW5kIDQuCiMgUmVzdWx0IGlzIHdyaXR0ZW4gaW50byBh\nZGRyZXNzIDkKIyAKIyBUbyBzZXQgaW5pdGlhbCB2YWx1ZXMgZm9yIFJhbS9SZWdpc3RlcnMKIyBk\nb3VibGUgY2xpY2sgYW55IGxpbmUgKG9uIHRoZSBsZWZ0IC0tPikKIyBhbmQgY29uZmlybSB3aXRo\nICplbnRlciogb3Igd2l0aCBjbGlja2luZwojIG5leHQgdG8gdGhlIGlucHV0IGZpZWxkLgojCiMg\nRnVuIHN0YXJ0cyBoZXJlOgpSNzwtbHNoKDErMSkgIyBsZWZ0c2hpZnQsIGFmdGVyIGFkZGl0aW9u\nClI3PC1SNytSNwpSODwtMApSNjwtKDErMSkgIyBvcHRpb25hbCBwYXJlbnMKUjY8LVI2KzEKTUFS\nPC1SNjtyZCAjIFJlYWQgZnJvbSBSYW0gKGFkZHI9MykKcmQgIyBSYW0gbmVlZHMgdHdvIGN5Y2xl\ncyB0byBmZXRjaCBkYXRhClI5PC1NQlIgIyB3cml0ZSB0aGUgZmV0Y2hlZCBkYXRhIGludG8gcmVn\naXN0ZXIgUjkKUjY8LVI2KzEKTUFSPC1SNjtyZCAjIFJlYWQgZnJvbSBSYW0gKGFkZHI9NCkKcmQK\nUjEwPC1NQlIgIyB3cml0ZSB0aGUgZmV0Y2hlZCBkYXRhIGludG8gcmVnaXN0ZXIgUjEwCiMgSGVy\nZSBiYXNpY2FsbHkgc3RhcnRzIHRoZSBtdWx0aXBsaWNhdGlvbgojIGFuZCBlbmRzIGF0IGxhYmVs\nIDplbmRsb29wClI5PC1sc2goUjkrUjkpClI5PC1sc2goUjkrUjkpClI5PC1sc2goUjkrUjkpClI5\nPC1sc2goUjkrUjkpCiMgOmxhYmVsIGRlY2xhcmVzIGEgbGFiZWwsCiMgeW91IGNhbiBqdW1wIHRv\nIGl0IHdpdGggZ290byAubGFiZWwKKFI3KTsgaWYgWiBnb3RvIC5lbmRsb29wIDpzdGFydGxvb3AK\nUjg8LWxzaChSOCkKKH5SOSk7IGlmIE4gZ290byAuc2tpcApSODwtUjgrUjEwClI5PC1sc2goUjkp\nIDpza2lwClI3PC1SNysoLTEpCmdvdG8gLnN0YXJ0bG9vcApSNjwtUjYrUjYgOmVuZGxvb3AKUjY8\nLVI2KzEKTUFSPC1SNgpNQlI8LVI4O3dyICMgV3JpdGUgcmVzdWx0IHRvIFJhbSAoYWRkcj05KQp3\nciAjIFJhbSBuZWVkcyBhbHNvIHR3byBjeWNsZXMgdG8gd3JpdGUgZGF0YQ==\"" } ]
src/main.coffee
Dav1dde/Micro16
1
Parser = require 'parser' Disassembler = require 'disasm' EXAMPLE_CODE = " IyMjIE11bHRpcGxpY2F0aW9uIG9mIHR3byBudW1iZXJzCiMgVmFsdWVzIGFyZSBsb2FkZWQgZnJv bSBSYW0sCiMgYXQgYWRkcmVzc2VzIDMgYW5kIDQuCiMgUmVzdWx0IGlzIHdyaXR0ZW4gaW50byBh ZGRyZXNzIDkKIyAKIyBUbyBzZXQgaW5pdGlhbCB2YWx1ZXMgZm9yIFJhbS9SZWdpc3RlcnMKIyBk b3VibGUgY2xpY2sgYW55IGxpbmUgKG9uIHRoZSBsZWZ0IC0tPikKIyBhbmQgY29uZmlybSB3aXRo ICplbnRlciogb3Igd2l0aCBjbGlja2luZwojIG5leHQgdG8gdGhlIGlucHV0IGZpZWxkLgojCiMg RnVuIHN0YXJ0cyBoZXJlOgpSNzwtbHNoKDErMSkgIyBsZWZ0c2hpZnQsIGFmdGVyIGFkZGl0aW9u ClI3PC1SNytSNwpSODwtMApSNjwtKDErMSkgIyBvcHRpb25hbCBwYXJlbnMKUjY8LVI2KzEKTUFS PC1SNjtyZCAjIFJlYWQgZnJvbSBSYW0gKGFkZHI9MykKcmQgIyBSYW0gbmVlZHMgdHdvIGN5Y2xl cyB0byBmZXRjaCBkYXRhClI5PC1NQlIgIyB3cml0ZSB0aGUgZmV0Y2hlZCBkYXRhIGludG8gcmVn aXN0ZXIgUjkKUjY8LVI2KzEKTUFSPC1SNjtyZCAjIFJlYWQgZnJvbSBSYW0gKGFkZHI9NCkKcmQK UjEwPC1NQlIgIyB3cml0ZSB0aGUgZmV0Y2hlZCBkYXRhIGludG8gcmVnaXN0ZXIgUjEwCiMgSGVy ZSBiYXNpY2FsbHkgc3RhcnRzIHRoZSBtdWx0aXBsaWNhdGlvbgojIGFuZCBlbmRzIGF0IGxhYmVs IDplbmRsb29wClI5PC1sc2goUjkrUjkpClI5PC1sc2goUjkrUjkpClI5PC1sc2goUjkrUjkpClI5 PC1sc2goUjkrUjkpCiMgOmxhYmVsIGRlY2xhcmVzIGEgbGFiZWwsCiMgeW91IGNhbiBqdW1wIHRv IGl0IHdpdGggZ290byAubGFiZWwKKFI3KTsgaWYgWiBnb3RvIC5lbmRsb29wIDpzdGFydGxvb3AK Ujg8LWxzaChSOCkKKH5SOSk7IGlmIE4gZ290byAuc2tpcApSODwtUjgrUjEwClI5PC1sc2goUjkp IDpza2lwClI3PC1SNysoLTEpCmdvdG8gLnN0YXJ0bG9vcApSNjwtUjYrUjYgOmVuZGxvb3AKUjY8 LVI2KzEKTUFSPC1SNgpNQlI8LVI4O3dyICMgV3JpdGUgcmVzdWx0IHRvIFJhbSAoYWRkcj05KQp3 ciAjIFJhbSBuZWVkcyBhbHNvIHR3byBjeWNsZXMgdG8gd3JpdGUgZGF0YQ==" DISASM_HTML = '<div class="toolbar" class="container-fluid"> <div class="row-fluid"> <div class="span5 mrm15"> <div class="status"> <span class="label label-info">Status:</span> <span class="status-text" style="color: green">Ready!</span> </div> </div> <div class="span7 btn-group dropdown input-prepend"> <a class="pull-right btn load-emu">Load into Emulator</a> </div> </div> </div> <div class="container-fluid"></div> <div class="container-fluid" class="outerc"> <div class="row-fluid contents"> <div class="span4 CodeMirror-outer mrm15" id="code-outer"> <textarea id="disin"></textarea> </div> <div class="span6 mrm15 CodeMirror-outer"> <textarea id="disout" readonly="readonly"></textarea> </div> <div class="span2 CodeMirror-outer"> <textarea id="disinhex" readonly="readonly"></textarea> </div> </div> </div>' REGISTER_TABLE = '<table class="table table-condensed" id="reg-table"> <tr><th class="first-col">Register</th><th>Value</th></tr> <tr><td>0</td><td class="m16-reg-key-0">0</td></tr> <tr><td>1</td><td class="m16-reg-key-1">1</td></tr> <tr><td>-1</td><td class="m16-reg-key--1">-1</td></tr> <tr><td>PC</td><td class="m16-reg-key-PC">0</td></tr> <tr><td>R0</td><td class="m16-reg-key-R0">0</td></tr> <tr><td>R1</td><td class="m16-reg-key-R1">0</td></tr> <tr><td>R2</td><td class="m16-reg-key-R2">0</td></tr> <tr><td>R3</td><td class="m16-reg-key-R3">0</td></tr> <tr><td>R4</td><td class="m16-reg-key-R4">0</td></tr> <tr><td>R5</td><td class="m16-reg-key-R5">0</td></tr> <tr><td>R6</td><td class="m16-reg-key-R6">0</td></tr> <tr><td>R7</td><td class="m16-reg-key-R7">0</td></tr> <tr><td>R8</td><td class="m16-reg-key-R8">0</td></tr> <tr><td>R9</td><td class="m16-reg-key-R9">0</td></tr> <tr><td>R10</td><td class="m16-reg-key-R10">0</td></tr> <tr><td>AC</td><td class="m16-reg-key-AC">0</td></tr> <tr><td>MAR</td><td class="m16-reg-key-MAR">0</td></tr> <tr><td>MBR</td><td class="m16-reg-key-MBR">0</td></tr> </table> <table class="table table-condensed" id="flag-table"> <tr><th class="first-col">Flag</th><th>Value</th></tr> <tr><td>N</td><td class="m16-flag-n">0</td></tr> <tr><td>Z</td><td class="m16-flag-z">0</td></tr> </table> <a class="btn pull-right btn-small clear-register">Reset Register</a>' RAM_TABLE = '<div class="ram-options"> <input type="checkbox" name="ramautojump" id="ramautojump">Autojump to last modification</input> </div> <div class="ram-jump-to"> <div class="pre-input">Jump To: </div> <div class="input-right"><input type="text" placeholder="Address" id="ram-addr"></text></div> </div> <table class="table table-condensed" id="ram-table"> <tr><th class="first-col-ram">Address</th><th>Value</th></tr> <tr class="m16-ram-0"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-1"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-2"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-3"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-4"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-5"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-6"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-7"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-8"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-9"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-10"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-11"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-12"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-13"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-14"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-15"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> </table> <a class="btn pull-right btn-small clear-ram">Clear Ram</a>' BREAKPOINTS_TABLE = '<div>Click on the gutter to toggle Breakpoints.</div> <table class="table table-condensed" id="breakpoints-table"> <tr><th class="first-col-breakpoints">Line</th><th>Content</th><th class="last-col-breakpoints"></th></tr> <tr><td></td><td></td><td></td></tr> </table> <a class="btn pull-right btn-small rm-breakpoints">Remove all</a>' EMPTY_REGISTER = ({ "0": 0, "1": 1, "-1": -1, PC: 0, R0: 0, R1: 0, R2: 0, R3: 0, R4: 0, R5: 0, R6: 0, R7: 0, R8: 0, R9: 0, R10: 0, AC: 0, MBR: 0, MAR: 0 }) # only for 16bit numbers! toDecimal = (inp) -> return ((if (inp & (1 << 15)) > 0 then 0xffff << 16 else 0) | inp).toString() toBin = (inp) -> return (1 << 16 | (inp & 0xffff)).toString(2).slice(1) toHex = (inp) -> hex = (Number(inp) & 0xffff).toString(16) return "0x" + ("0000".substr(0, 4 - hex.length)) + hex.toUpperCase(); toHex2 = (inp) -> hex = ((Number(inp) & 0xffffffff) >>> 0).toString(16) return "0x" + ("00000000".substr(0, 8 - hex.length)) + hex.toUpperCase(); class EmulatorMain constructor: -> @code = window.cmCode = CodeMirror.fromTextArea(document.getElementById('code'), mode: 'micro16', tabSize: 4, smartIndent: false, lineNumbers: true, lineWrapping: false, firstLineNumber: 0 gutters:["breakpoints", "currentline", "CodeMirror-linenumbers"]) @asm = CodeMirror.fromTextArea(document.getElementById('out'), mode: 'none', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, firstLineNumber: 0) reinit: -> @parser = new Parser() @mic = null @convertFunc = null @updateConvertFunc("binary") @breakpoints = {} @lastBreak = -1 @isDone = false @userRegister = $.extend({}, EMPTY_REGISTER) @lastRegister = $.extend({}, EMPTY_REGISTER) @lastFlags = {"N" : 0, "Z": 0} @userRam = new Array(Math.pow(2, 16)) for element, i in @userRam @userRam[i] = 0 @ramStartPos = 0 @lastErrorLine = -1 @code.on("change", (cm, change) => @parser = new Parser() $("#run").removeAttr("disabled") $("#step").removeAttr("disabled") $("#pause").removeAttr("disabled") $("#reset").removeAttr("disabled") $(".status-text").text("Stopped") $(".status-text").css("color", "green") if @lastErrorLine >= 0 @asm.removeLineClass(@lastErrorLine, "background") try @parser.parse @code.getValue() catch error if error.name != "SyntaxError" then throw error #console.log error $("#run").attr("disabled", "disabled") $("#step").attr("disabled", "disabled") $("#pause").attr("disabled", "disabled") $("#reset").attr("disabled", "disabled") $(".status-text").text(error.message + (if error.line != undefined then " | At line: " + error.line else "")) $(".status-text").css("color", "red") @lastErrorLine = error.line #if error.line? # @asm.addLineClass(error.line, "background", "code-error-bg") return if @code.getValue() $("#share").val(location.href.replace(/#.*$/, "") + "#&inp=" + $.base64("btoa", @code.getValue())) @setValueAsm() @code.clearGutter("currentline") if change.text.length > 1 then @updateBreakpointLines() @makeMic() ) @code.on("gutterClick", (cm, n) => info = cm.lineInfo(n) marker = document.createElement("div"); marker.innerHTML = "&bull;"; marker.className = "breakpoint"; cm.setGutterMarker(n, "breakpoints", if info.gutterMarkers?.breakpoints then null else marker); @updateBreakpointLines() ) $("#step").click => @mic.step() if !@mic.isFinished() then $(".status-text").text("Paused") $("#reset").click => @code.setGutterMarker((if @mic? then @mic.addr else 0), "currentline", null) @mic.pause() @makeMic() @updateRegistersRam() $("#run").click => @mic.run() if not @isDone $("#run").attr("disabled", "disabled") $("#step").attr("disabled", "disabled") $("#pause").removeAttr("disabled") $(".status-text").text("Running") $("#pause").click => @mic.pause() $("#pause").attr("disabled", "disabled") $("#step").removeAttr("disabled") $("#run").removeAttr("disabled") $(".status-text").text("Paused" + if @breakpoints[@mic.addr] then " (Breakpoint)" else "") $("#clockSpeed").keyup => value = parseInt($("#clockSpeed").val()) @mic.setSpeed(if value then value else 1) $("#clockSpeed").change => value = parseInt($("#clockSpeed").val()) @mic.setSpeed(if value then value else 1) @visible = "register" $(".btn-register").click => $(".btn-register").parent().parent().find(".active").removeClass("active") $(".btn-register").parent().addClass("active") @visible = "register" $("#info").children().remove() $("#info").append(REGISTER_TABLE) @updateRegistersRam() $("#reg-table tbody tr:gt(3)").dblclick (event) => Jregister = $("td:nth-child(2)", $(event.target).parent()) register = Jregister.attr("class").match(/\w+$/) Jregister.text("") inp = $('<input type="text" data-toggle="tooltip" class="inj-reg"></input>') .css("margin", "0") .css("padding", "0") .css("height", Jregister.height()-2 + "px") .css("width", "150px") .attr("title", "Invalid Input. Correct Unit?") .data({register: register}) .appendTo(Jregister) inp.keypress (event) => if event.which == 13 then Jregister.click() #inp.tooltip() $("#reg-table tbody tr:gt(3)").click (event) => Jregister = $("td:nth-child(2)", $(event.target).parent()) inp = Jregister.find("input") register = $("td:nth-child(1)", $(event.target).parent()).text() text = inp.val() value = switch when not text then 0 when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(value) inp.tooltip() inp.tooltip("show") setTimeout((() => inp.tooltip("destroy")), 1100) return @userRegister[register] = value reg = @userRegister if @mic @mic.vm.register[register] = value reg = @mic.vm.register Jregister.text(@convertFunc reg[register]) $(".clear-register").click => @userRegister = $.extend({}, EMPTY_REGISTER) @updateRegistersRam() $(".btn-ram").click => $(".btn-ram").parent().parent().find(".active").removeClass("active") $(".btn-ram").parent().addClass("active") @visible = "ram" $("#info").children().remove() $("#info").append(RAM_TABLE) @updateRegistersRam() $("#ram-addr").keyup => text = $("#ram-addr").val() @ramStartPos = switch when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(@ramStartPos) and @ramStartPos? @ramStartPos = 0 @updateRegistersRam() $("#ram-table tbody tr:gt(0)").dblclick (event) => Jram = $("td:nth-child(2)", $(event.target).parent()) ramcol = Jram.parent().attr("class").match(/\w+$/) Jram.text("") inp = $('<input type="text" data-toggle="tooltip" class="inj-reg"></input>') .css("margin", "0") .css("padding", "0") .css("height", Jram.height()-2 + "px") .css("width", "150px") .attr("title", "Invalid Input. Correct Unit?") .data({ram: ramcol}) .appendTo(Jram) inp.keypress (event) => if event.which == 13 then Jram.click() $("#ram-table tbody tr:gt(0)").click (event) => Jram = $("td:nth-child(2)", $(event.target).parent()) inp = Jram.find("input") ramAddr = $("td:nth-child(1) span:nth-child(1)", $(event.target).parent()).text() ramAddr = parseInt(ramAddr, 16) text = inp.val() value = switch when not text then 0 when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(value) inp.tooltip() inp.tooltip("show") setTimeout((() => inp.tooltip("destroy")), 1100) return @userRam[ramAddr] = value ram = @userRam if @mic @mic.vm.ram.ram[ramAddr] = value ram = @mic.vm.ram.ram Jram.text(@convertFunc ram[ramAddr]) $(".clear-ram").click => for element, i in @userRam @userRam[i] = 0 @updateRegistersRam() $(".btn-breakpoints").click => $(".btn-breakpoints").parent().parent().find(".active").removeClass("active") $(".btn-breakpoints").parent().addClass("active") @visible = "breakpoints" $("#info").children().remove() $("#info").append(BREAKPOINTS_TABLE) @updateRegistersRam() $(".rm-breakpoints").click => @breakpoints = {} @code.clearGutter("breakpoints") @updateBreakpointLines() $(".load-example").click => $("#aboutModal").modal('hide') @code.setValue($.base64('atob', EXAMPLE_CODE)) # tab which is open by default $(".btn-register").click() $(".unit-binary").click => @updateConvertFunc "binary" @updateRegistersRam() $(".unit-decimal").click => @updateConvertFunc "decimal" @updateRegistersRam() $(".unit-hexadecimal").click => @updateConvertFunc "hexadecimal" @updateRegistersRam() inp = HashSearch.get("inp") if inp then @code.setValue($.base64("atob", inp)) HashSearch.remove("inp") @code.setValue(@code.getValue()) # trigger change makeMic: -> @mic = null @updateRegistersRam() @mic = @parser.makeMic() @mic.vm.register = $.extend({}, @userRegister) @mic.vm.ram.ram = @userRam.slice() @mic.events.on("step", => if @breakpoints[@mic.addr] and @mic.clock.started and @lastBreak != @mic.addr @lastBreak = @mic.addr $("#pause").click() return @lastBreak = -1 @code.setGutterMarker(@mic.addr, "currentline", null) ) @mic.events.on("stepped", => @updateRegistersRam()) @mic.events.on("stop", => @isDone = true $("#step").attr("disabled", "disabled") $("#run").attr("disabled", "disabled") $("#pause").attr("disabled", "disabled") $(".status-text").text("Finished") ) @mic.setSpeed(parseInt($("#clockSpeed").val()) or 1) $("#step").removeAttr("disabled") $("#run").removeAttr("disabled") $("#pause").removeAttr("disabled") $("#pause").attr("disabled", "disabled") $(".status-text").text("Stopped") @mic.vm.ram.events.on("write", (pos, data) => if $("input[name=ramautojump]").prop("checked") then @ramStartPos = pos @updateRegistersRam() ) @mic.vm.ram.events.on("read", (pos) => @updateRegistersRam()) updateRegistersRam: -> switch @visible when "register" then @updateRegisters() when "ram" then @updateRam() when "breakpoints" then @updateBreakpoints() @code.clearGutter("currentline") @setGutterMark(if @mic? then @mic.addr else 0) updateRegisters: -> registers = if @mic? then @mic.vm.register else @userRegister flags = if @mic? then @mic.vm.flags else @lastFlags for own key, value of registers j = $(".m16-reg-key-" + key) j.parent().removeClass("info") if @lastRegister[key] != value then j.parent().addClass("info") j.text(@convertFunc value) for f in ["N", "Z"] j = $(".m16-flag-" + f.toLowerCase()) j.parent().removeClass("info") if @lastFlags[f] != flags[f] then j.parent().addClass("info"); j.text(@convertFunc flags[f]) @lastRegister = registers @lastFlags = flags updateRam: -> ram = if @mic? then @mic.vm.ram else {get: (i) => @userRam[i]} for i in [0..15] ii = @ramStartPos+i s = ".m16-ram-" + i #rotate! $(s + " td:last-child").text(@convertFunc ram.get(parseInt(toDecimal(toBin(ii)), 2))) $(s + " td:first-child span:nth-child(1)") .text(toHex(ii)) $(s + " td:first-child span:nth-child(2)") .text(toBin(ii)) updateBreakpointLines: -> @breakpoints = {} @code.eachLine (handle) => info = @code.lineInfo(handle) line = info.line if info.gutterMarkers?.breakpoints @breakpoints[line] = true return if @visible == "breakpoints" @updateBreakpoints() updateBreakpoints: -> $("#breakpoints-table tbody tr:gt(1)").remove() for key, value of @breakpoints $("<tr></tr>") .append($("<td></td>").text(key)) .append($("<td></td>").text(@code.getLineHandle(key).text)) .append($("<td></td>") .html('<i class="icon-remove"></i>') .click => @code.setGutterMarker(@code.getLineHandle(key), "breakpoints", null) @updateBreakpointLines() ) .appendTo("#breakpoints-table tbody") setGutterMark: (addr) -> element = document.createElement("div") element.innerHTML = "&rarr;" @code.setGutterMarker((if addr? then addr else @mic.attr), "currentline", element) updateConvertFunc: (unit) -> $(".unit-binary").parent().parent().find("i").remove() @unitMode = unit switch unit when "decimal" $(".unit-decimal").html('Decimal <i class="icon-ok">') @convertFunc = toDecimal when "hexadecimal" $(".unit-hexadecimal").html('Hexadecimal <i class="icon-ok">') @convertFunc = (inp) -> return toHex(toDecimal(inp)) else $(".unit-binary").html('Binary <i class="icon-ok">') @convertFunc = toBin @unitMode = "binary" @setValueAsm() setValueAsm: -> @asm.setValue($.map(@parser.getFormattedIns("").replace(/\s+$/, "").split("\n"), (x, i) => switch @unitMode when x == undefined or x == null or x.length == 0 then return "" when "decimal" then return x when "hexadecimal" then return toHex2(parseInt(x, 2)) else return x ).join("\n").replace(/\s+$/, "")) class DisassemblerMain constructor: -> @disin = CodeMirror.fromTextArea(document.getElementById('disin'), mode: 'none', tabSize: 4, smartIndent: false, lineNumbers: true, lineWrapping: false, firstLineNumber: 0 ) @disout = CodeMirror.fromTextArea(document.getElementById('disout'), mode: 'micro16', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, gutter: false, firstLineNumber: 0 ) @disinhex = CodeMirror.fromTextArea(document.getElementById('disinhex'), mode: 'none', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, gutter: false, firstLineNumber: 0 ) disassembler = new Disassembler() @disin.on("change", (cm, change) => $(".status-text").text("Everything fine!") $(".status-text").css("color", "green") out = null try out = disassembler.disassembleLines(@disin.getValue()) catch error if error.name != "DisassemblerError" then throw error @disout.setValue("") $(".status-text").text(error.message + (if error.line != undefined then " | At line: " + error.line else "")) $(".status-text").css("color", "red") return if @disin.getValue() $("#share").val(location.href.replace(/#.*$/, "") + "#disasm&inp=" + $.base64("btoa", @disin.getValue())) @disout.setValue out["dis"].join("\n") @disinhex.setValue $.map(out["ins"], (x, i) -> toHex2(x)).join("\n") ) reinit: -> $(".load-emu").click => $("#switchEmu").click() window.cmCode.setValue(@disout.getValue()) inp = HashSearch.get("inp") if inp then @disin.setValue($.base64("atob", inp)) HashSearch.remove("inp") @disin.setValue(@disin.getValue()) # trigger change # main entry point $ -> HashSearch.load() emulator = $("#outer").children() disassembler = $(DISASM_HTML) current = null cls = {} resize = -> height = $(window).height() - 120 height5 = height / 5 $(".CodeMirror").height(height) $("#register").height(height5 * 3) $("#ram").height(height5 * 2) $("#disin").height(height5 * 3) $("#disout").height(height5 * 2) $("#switchDis").click => if current == "disassembler" then return else current = "disassembler" if not HashSearch.keyExists("disasm") then HashSearch.set("disasm") $("#switchDis").parent().parent().find(".active").removeClass("active") $("#switchDis").parent().addClass("active") $("#outer").children().remove() $("#outer").append(disassembler) if not cls[current] then cls[current] = new DisassemblerMain() cls[current].reinit() resize() $("#switchEmu").click => if current == "emulator" then return else current = "emulator" HashSearch.remove("disasm") $("#switchEmu").parent().parent().find(".active").removeClass("active") $("#switchEmu").parent().addClass("active") $("#outer").children().remove() $("#outer").append(emulator) if not cls[current] then cls[current] = new EmulatorMain() cls[current].reinit() resize() if HashSearch.keyExists("disasm") $("#switchDis").click() else $("#switchEmu").click() $(window).resize resize resize()
130528
Parser = require 'parser' Disassembler = require 'disasm' EXAMPLE_CODE = " <KEY> DISASM_HTML = '<div class="toolbar" class="container-fluid"> <div class="row-fluid"> <div class="span5 mrm15"> <div class="status"> <span class="label label-info">Status:</span> <span class="status-text" style="color: green">Ready!</span> </div> </div> <div class="span7 btn-group dropdown input-prepend"> <a class="pull-right btn load-emu">Load into Emulator</a> </div> </div> </div> <div class="container-fluid"></div> <div class="container-fluid" class="outerc"> <div class="row-fluid contents"> <div class="span4 CodeMirror-outer mrm15" id="code-outer"> <textarea id="disin"></textarea> </div> <div class="span6 mrm15 CodeMirror-outer"> <textarea id="disout" readonly="readonly"></textarea> </div> <div class="span2 CodeMirror-outer"> <textarea id="disinhex" readonly="readonly"></textarea> </div> </div> </div>' REGISTER_TABLE = '<table class="table table-condensed" id="reg-table"> <tr><th class="first-col">Register</th><th>Value</th></tr> <tr><td>0</td><td class="m16-reg-key-0">0</td></tr> <tr><td>1</td><td class="m16-reg-key-1">1</td></tr> <tr><td>-1</td><td class="m16-reg-key--1">-1</td></tr> <tr><td>PC</td><td class="m16-reg-key-PC">0</td></tr> <tr><td>R0</td><td class="m16-reg-key-R0">0</td></tr> <tr><td>R1</td><td class="m16-reg-key-R1">0</td></tr> <tr><td>R2</td><td class="m16-reg-key-R2">0</td></tr> <tr><td>R3</td><td class="m16-reg-key-R3">0</td></tr> <tr><td>R4</td><td class="m16-reg-key-R4">0</td></tr> <tr><td>R5</td><td class="m16-reg-key-R5">0</td></tr> <tr><td>R6</td><td class="m16-reg-key-R6">0</td></tr> <tr><td>R7</td><td class="m16-reg-key-R7">0</td></tr> <tr><td>R8</td><td class="m16-reg-key-R8">0</td></tr> <tr><td>R9</td><td class="m16-reg-key-R9">0</td></tr> <tr><td>R10</td><td class="m16-reg-key-R10">0</td></tr> <tr><td>AC</td><td class="m16-reg-key-AC">0</td></tr> <tr><td>MAR</td><td class="m16-reg-key-MAR">0</td></tr> <tr><td>MBR</td><td class="m16-reg-key-MBR">0</td></tr> </table> <table class="table table-condensed" id="flag-table"> <tr><th class="first-col">Flag</th><th>Value</th></tr> <tr><td>N</td><td class="m16-flag-n">0</td></tr> <tr><td>Z</td><td class="m16-flag-z">0</td></tr> </table> <a class="btn pull-right btn-small clear-register">Reset Register</a>' RAM_TABLE = '<div class="ram-options"> <input type="checkbox" name="ramautojump" id="ramautojump">Autojump to last modification</input> </div> <div class="ram-jump-to"> <div class="pre-input">Jump To: </div> <div class="input-right"><input type="text" placeholder="Address" id="ram-addr"></text></div> </div> <table class="table table-condensed" id="ram-table"> <tr><th class="first-col-ram">Address</th><th>Value</th></tr> <tr class="m16-ram-0"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-1"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-2"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-3"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-4"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-5"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-6"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-7"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-8"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-9"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-10"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-11"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-12"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-13"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-14"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-15"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> </table> <a class="btn pull-right btn-small clear-ram">Clear Ram</a>' BREAKPOINTS_TABLE = '<div>Click on the gutter to toggle Breakpoints.</div> <table class="table table-condensed" id="breakpoints-table"> <tr><th class="first-col-breakpoints">Line</th><th>Content</th><th class="last-col-breakpoints"></th></tr> <tr><td></td><td></td><td></td></tr> </table> <a class="btn pull-right btn-small rm-breakpoints">Remove all</a>' EMPTY_REGISTER = ({ "0": 0, "1": 1, "-1": -1, PC: 0, R0: 0, R1: 0, R2: 0, R3: 0, R4: 0, R5: 0, R6: 0, R7: 0, R8: 0, R9: 0, R10: 0, AC: 0, MBR: 0, MAR: 0 }) # only for 16bit numbers! toDecimal = (inp) -> return ((if (inp & (1 << 15)) > 0 then 0xffff << 16 else 0) | inp).toString() toBin = (inp) -> return (1 << 16 | (inp & 0xffff)).toString(2).slice(1) toHex = (inp) -> hex = (Number(inp) & 0xffff).toString(16) return "0x" + ("0000".substr(0, 4 - hex.length)) + hex.toUpperCase(); toHex2 = (inp) -> hex = ((Number(inp) & 0xffffffff) >>> 0).toString(16) return "0x" + ("00000000".substr(0, 8 - hex.length)) + hex.toUpperCase(); class EmulatorMain constructor: -> @code = window.cmCode = CodeMirror.fromTextArea(document.getElementById('code'), mode: 'micro16', tabSize: 4, smartIndent: false, lineNumbers: true, lineWrapping: false, firstLineNumber: 0 gutters:["breakpoints", "currentline", "CodeMirror-linenumbers"]) @asm = CodeMirror.fromTextArea(document.getElementById('out'), mode: 'none', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, firstLineNumber: 0) reinit: -> @parser = new Parser() @mic = null @convertFunc = null @updateConvertFunc("binary") @breakpoints = {} @lastBreak = -1 @isDone = false @userRegister = $.extend({}, EMPTY_REGISTER) @lastRegister = $.extend({}, EMPTY_REGISTER) @lastFlags = {"N" : 0, "Z": 0} @userRam = new Array(Math.pow(2, 16)) for element, i in @userRam @userRam[i] = 0 @ramStartPos = 0 @lastErrorLine = -1 @code.on("change", (cm, change) => @parser = new Parser() $("#run").removeAttr("disabled") $("#step").removeAttr("disabled") $("#pause").removeAttr("disabled") $("#reset").removeAttr("disabled") $(".status-text").text("Stopped") $(".status-text").css("color", "green") if @lastErrorLine >= 0 @asm.removeLineClass(@lastErrorLine, "background") try @parser.parse @code.getValue() catch error if error.name != "SyntaxError" then throw error #console.log error $("#run").attr("disabled", "disabled") $("#step").attr("disabled", "disabled") $("#pause").attr("disabled", "disabled") $("#reset").attr("disabled", "disabled") $(".status-text").text(error.message + (if error.line != undefined then " | At line: " + error.line else "")) $(".status-text").css("color", "red") @lastErrorLine = error.line #if error.line? # @asm.addLineClass(error.line, "background", "code-error-bg") return if @code.getValue() $("#share").val(location.href.replace(/#.*$/, "") + "#&inp=" + $.base64("btoa", @code.getValue())) @setValueAsm() @code.clearGutter("currentline") if change.text.length > 1 then @updateBreakpointLines() @makeMic() ) @code.on("gutterClick", (cm, n) => info = cm.lineInfo(n) marker = document.createElement("div"); marker.innerHTML = "&bull;"; marker.className = "breakpoint"; cm.setGutterMarker(n, "breakpoints", if info.gutterMarkers?.breakpoints then null else marker); @updateBreakpointLines() ) $("#step").click => @mic.step() if !@mic.isFinished() then $(".status-text").text("Paused") $("#reset").click => @code.setGutterMarker((if @mic? then @mic.addr else 0), "currentline", null) @mic.pause() @makeMic() @updateRegistersRam() $("#run").click => @mic.run() if not @isDone $("#run").attr("disabled", "disabled") $("#step").attr("disabled", "disabled") $("#pause").removeAttr("disabled") $(".status-text").text("Running") $("#pause").click => @mic.pause() $("#pause").attr("disabled", "disabled") $("#step").removeAttr("disabled") $("#run").removeAttr("disabled") $(".status-text").text("Paused" + if @breakpoints[@mic.addr] then " (Breakpoint)" else "") $("#clockSpeed").keyup => value = parseInt($("#clockSpeed").val()) @mic.setSpeed(if value then value else 1) $("#clockSpeed").change => value = parseInt($("#clockSpeed").val()) @mic.setSpeed(if value then value else 1) @visible = "register" $(".btn-register").click => $(".btn-register").parent().parent().find(".active").removeClass("active") $(".btn-register").parent().addClass("active") @visible = "register" $("#info").children().remove() $("#info").append(REGISTER_TABLE) @updateRegistersRam() $("#reg-table tbody tr:gt(3)").dblclick (event) => Jregister = $("td:nth-child(2)", $(event.target).parent()) register = Jregister.attr("class").match(/\w+$/) Jregister.text("") inp = $('<input type="text" data-toggle="tooltip" class="inj-reg"></input>') .css("margin", "0") .css("padding", "0") .css("height", Jregister.height()-2 + "px") .css("width", "150px") .attr("title", "Invalid Input. Correct Unit?") .data({register: register}) .appendTo(Jregister) inp.keypress (event) => if event.which == 13 then Jregister.click() #inp.tooltip() $("#reg-table tbody tr:gt(3)").click (event) => Jregister = $("td:nth-child(2)", $(event.target).parent()) inp = Jregister.find("input") register = $("td:nth-child(1)", $(event.target).parent()).text() text = inp.val() value = switch when not text then 0 when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(value) inp.tooltip() inp.tooltip("show") setTimeout((() => inp.tooltip("destroy")), 1100) return @userRegister[register] = value reg = @userRegister if @mic @mic.vm.register[register] = value reg = @mic.vm.register Jregister.text(@convertFunc reg[register]) $(".clear-register").click => @userRegister = $.extend({}, EMPTY_REGISTER) @updateRegistersRam() $(".btn-ram").click => $(".btn-ram").parent().parent().find(".active").removeClass("active") $(".btn-ram").parent().addClass("active") @visible = "ram" $("#info").children().remove() $("#info").append(RAM_TABLE) @updateRegistersRam() $("#ram-addr").keyup => text = $("#ram-addr").val() @ramStartPos = switch when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(@ramStartPos) and @ramStartPos? @ramStartPos = 0 @updateRegistersRam() $("#ram-table tbody tr:gt(0)").dblclick (event) => Jram = $("td:nth-child(2)", $(event.target).parent()) ramcol = Jram.parent().attr("class").match(/\w+$/) Jram.text("") inp = $('<input type="text" data-toggle="tooltip" class="inj-reg"></input>') .css("margin", "0") .css("padding", "0") .css("height", Jram.height()-2 + "px") .css("width", "150px") .attr("title", "Invalid Input. Correct Unit?") .data({ram: ramcol}) .appendTo(Jram) inp.keypress (event) => if event.which == 13 then Jram.click() $("#ram-table tbody tr:gt(0)").click (event) => Jram = $("td:nth-child(2)", $(event.target).parent()) inp = Jram.find("input") ramAddr = $("td:nth-child(1) span:nth-child(1)", $(event.target).parent()).text() ramAddr = parseInt(ramAddr, 16) text = inp.val() value = switch when not text then 0 when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(value) inp.tooltip() inp.tooltip("show") setTimeout((() => inp.tooltip("destroy")), 1100) return @userRam[ramAddr] = value ram = @userRam if @mic @mic.vm.ram.ram[ramAddr] = value ram = @mic.vm.ram.ram Jram.text(@convertFunc ram[ramAddr]) $(".clear-ram").click => for element, i in @userRam @userRam[i] = 0 @updateRegistersRam() $(".btn-breakpoints").click => $(".btn-breakpoints").parent().parent().find(".active").removeClass("active") $(".btn-breakpoints").parent().addClass("active") @visible = "breakpoints" $("#info").children().remove() $("#info").append(BREAKPOINTS_TABLE) @updateRegistersRam() $(".rm-breakpoints").click => @breakpoints = {} @code.clearGutter("breakpoints") @updateBreakpointLines() $(".load-example").click => $("#aboutModal").modal('hide') @code.setValue($.base64('atob', EXAMPLE_CODE)) # tab which is open by default $(".btn-register").click() $(".unit-binary").click => @updateConvertFunc "binary" @updateRegistersRam() $(".unit-decimal").click => @updateConvertFunc "decimal" @updateRegistersRam() $(".unit-hexadecimal").click => @updateConvertFunc "hexadecimal" @updateRegistersRam() inp = HashSearch.get("inp") if inp then @code.setValue($.base64("atob", inp)) HashSearch.remove("inp") @code.setValue(@code.getValue()) # trigger change makeMic: -> @mic = null @updateRegistersRam() @mic = @parser.makeMic() @mic.vm.register = $.extend({}, @userRegister) @mic.vm.ram.ram = @userRam.slice() @mic.events.on("step", => if @breakpoints[@mic.addr] and @mic.clock.started and @lastBreak != @mic.addr @lastBreak = @mic.addr $("#pause").click() return @lastBreak = -1 @code.setGutterMarker(@mic.addr, "currentline", null) ) @mic.events.on("stepped", => @updateRegistersRam()) @mic.events.on("stop", => @isDone = true $("#step").attr("disabled", "disabled") $("#run").attr("disabled", "disabled") $("#pause").attr("disabled", "disabled") $(".status-text").text("Finished") ) @mic.setSpeed(parseInt($("#clockSpeed").val()) or 1) $("#step").removeAttr("disabled") $("#run").removeAttr("disabled") $("#pause").removeAttr("disabled") $("#pause").attr("disabled", "disabled") $(".status-text").text("Stopped") @mic.vm.ram.events.on("write", (pos, data) => if $("input[name=ramautojump]").prop("checked") then @ramStartPos = pos @updateRegistersRam() ) @mic.vm.ram.events.on("read", (pos) => @updateRegistersRam()) updateRegistersRam: -> switch @visible when "register" then @updateRegisters() when "ram" then @updateRam() when "breakpoints" then @updateBreakpoints() @code.clearGutter("currentline") @setGutterMark(if @mic? then @mic.addr else 0) updateRegisters: -> registers = if @mic? then @mic.vm.register else @userRegister flags = if @mic? then @mic.vm.flags else @lastFlags for own key, value of registers j = $(".m16-reg-key-" + key) j.parent().removeClass("info") if @lastRegister[key] != value then j.parent().addClass("info") j.text(@convertFunc value) for f in ["N", "Z"] j = $(".m16-flag-" + f.toLowerCase()) j.parent().removeClass("info") if @lastFlags[f] != flags[f] then j.parent().addClass("info"); j.text(@convertFunc flags[f]) @lastRegister = registers @lastFlags = flags updateRam: -> ram = if @mic? then @mic.vm.ram else {get: (i) => @userRam[i]} for i in [0..15] ii = @ramStartPos+i s = ".m16-ram-" + i #rotate! $(s + " td:last-child").text(@convertFunc ram.get(parseInt(toDecimal(toBin(ii)), 2))) $(s + " td:first-child span:nth-child(1)") .text(toHex(ii)) $(s + " td:first-child span:nth-child(2)") .text(toBin(ii)) updateBreakpointLines: -> @breakpoints = {} @code.eachLine (handle) => info = @code.lineInfo(handle) line = info.line if info.gutterMarkers?.breakpoints @breakpoints[line] = true return if @visible == "breakpoints" @updateBreakpoints() updateBreakpoints: -> $("#breakpoints-table tbody tr:gt(1)").remove() for key, value of @breakpoints $("<tr></tr>") .append($("<td></td>").text(key)) .append($("<td></td>").text(@code.getLineHandle(key).text)) .append($("<td></td>") .html('<i class="icon-remove"></i>') .click => @code.setGutterMarker(@code.getLineHandle(key), "breakpoints", null) @updateBreakpointLines() ) .appendTo("#breakpoints-table tbody") setGutterMark: (addr) -> element = document.createElement("div") element.innerHTML = "&rarr;" @code.setGutterMarker((if addr? then addr else @mic.attr), "currentline", element) updateConvertFunc: (unit) -> $(".unit-binary").parent().parent().find("i").remove() @unitMode = unit switch unit when "decimal" $(".unit-decimal").html('Decimal <i class="icon-ok">') @convertFunc = toDecimal when "hexadecimal" $(".unit-hexadecimal").html('Hexadecimal <i class="icon-ok">') @convertFunc = (inp) -> return toHex(toDecimal(inp)) else $(".unit-binary").html('Binary <i class="icon-ok">') @convertFunc = toBin @unitMode = "binary" @setValueAsm() setValueAsm: -> @asm.setValue($.map(@parser.getFormattedIns("").replace(/\s+$/, "").split("\n"), (x, i) => switch @unitMode when x == undefined or x == null or x.length == 0 then return "" when "decimal" then return x when "hexadecimal" then return toHex2(parseInt(x, 2)) else return x ).join("\n").replace(/\s+$/, "")) class DisassemblerMain constructor: -> @disin = CodeMirror.fromTextArea(document.getElementById('disin'), mode: 'none', tabSize: 4, smartIndent: false, lineNumbers: true, lineWrapping: false, firstLineNumber: 0 ) @disout = CodeMirror.fromTextArea(document.getElementById('disout'), mode: 'micro16', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, gutter: false, firstLineNumber: 0 ) @disinhex = CodeMirror.fromTextArea(document.getElementById('disinhex'), mode: 'none', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, gutter: false, firstLineNumber: 0 ) disassembler = new Disassembler() @disin.on("change", (cm, change) => $(".status-text").text("Everything fine!") $(".status-text").css("color", "green") out = null try out = disassembler.disassembleLines(@disin.getValue()) catch error if error.name != "DisassemblerError" then throw error @disout.setValue("") $(".status-text").text(error.message + (if error.line != undefined then " | At line: " + error.line else "")) $(".status-text").css("color", "red") return if @disin.getValue() $("#share").val(location.href.replace(/#.*$/, "") + "#disasm&inp=" + $.base64("btoa", @disin.getValue())) @disout.setValue out["dis"].join("\n") @disinhex.setValue $.map(out["ins"], (x, i) -> toHex2(x)).join("\n") ) reinit: -> $(".load-emu").click => $("#switchEmu").click() window.cmCode.setValue(@disout.getValue()) inp = HashSearch.get("inp") if inp then @disin.setValue($.base64("atob", inp)) HashSearch.remove("inp") @disin.setValue(@disin.getValue()) # trigger change # main entry point $ -> HashSearch.load() emulator = $("#outer").children() disassembler = $(DISASM_HTML) current = null cls = {} resize = -> height = $(window).height() - 120 height5 = height / 5 $(".CodeMirror").height(height) $("#register").height(height5 * 3) $("#ram").height(height5 * 2) $("#disin").height(height5 * 3) $("#disout").height(height5 * 2) $("#switchDis").click => if current == "disassembler" then return else current = "disassembler" if not HashSearch.keyExists("disasm") then HashSearch.set("disasm") $("#switchDis").parent().parent().find(".active").removeClass("active") $("#switchDis").parent().addClass("active") $("#outer").children().remove() $("#outer").append(disassembler) if not cls[current] then cls[current] = new DisassemblerMain() cls[current].reinit() resize() $("#switchEmu").click => if current == "emulator" then return else current = "emulator" HashSearch.remove("disasm") $("#switchEmu").parent().parent().find(".active").removeClass("active") $("#switchEmu").parent().addClass("active") $("#outer").children().remove() $("#outer").append(emulator) if not cls[current] then cls[current] = new EmulatorMain() cls[current].reinit() resize() if HashSearch.keyExists("disasm") $("#switchDis").click() else $("#switchEmu").click() $(window).resize resize resize()
true
Parser = require 'parser' Disassembler = require 'disasm' EXAMPLE_CODE = " PI:KEY:<KEY>END_PI DISASM_HTML = '<div class="toolbar" class="container-fluid"> <div class="row-fluid"> <div class="span5 mrm15"> <div class="status"> <span class="label label-info">Status:</span> <span class="status-text" style="color: green">Ready!</span> </div> </div> <div class="span7 btn-group dropdown input-prepend"> <a class="pull-right btn load-emu">Load into Emulator</a> </div> </div> </div> <div class="container-fluid"></div> <div class="container-fluid" class="outerc"> <div class="row-fluid contents"> <div class="span4 CodeMirror-outer mrm15" id="code-outer"> <textarea id="disin"></textarea> </div> <div class="span6 mrm15 CodeMirror-outer"> <textarea id="disout" readonly="readonly"></textarea> </div> <div class="span2 CodeMirror-outer"> <textarea id="disinhex" readonly="readonly"></textarea> </div> </div> </div>' REGISTER_TABLE = '<table class="table table-condensed" id="reg-table"> <tr><th class="first-col">Register</th><th>Value</th></tr> <tr><td>0</td><td class="m16-reg-key-0">0</td></tr> <tr><td>1</td><td class="m16-reg-key-1">1</td></tr> <tr><td>-1</td><td class="m16-reg-key--1">-1</td></tr> <tr><td>PC</td><td class="m16-reg-key-PC">0</td></tr> <tr><td>R0</td><td class="m16-reg-key-R0">0</td></tr> <tr><td>R1</td><td class="m16-reg-key-R1">0</td></tr> <tr><td>R2</td><td class="m16-reg-key-R2">0</td></tr> <tr><td>R3</td><td class="m16-reg-key-R3">0</td></tr> <tr><td>R4</td><td class="m16-reg-key-R4">0</td></tr> <tr><td>R5</td><td class="m16-reg-key-R5">0</td></tr> <tr><td>R6</td><td class="m16-reg-key-R6">0</td></tr> <tr><td>R7</td><td class="m16-reg-key-R7">0</td></tr> <tr><td>R8</td><td class="m16-reg-key-R8">0</td></tr> <tr><td>R9</td><td class="m16-reg-key-R9">0</td></tr> <tr><td>R10</td><td class="m16-reg-key-R10">0</td></tr> <tr><td>AC</td><td class="m16-reg-key-AC">0</td></tr> <tr><td>MAR</td><td class="m16-reg-key-MAR">0</td></tr> <tr><td>MBR</td><td class="m16-reg-key-MBR">0</td></tr> </table> <table class="table table-condensed" id="flag-table"> <tr><th class="first-col">Flag</th><th>Value</th></tr> <tr><td>N</td><td class="m16-flag-n">0</td></tr> <tr><td>Z</td><td class="m16-flag-z">0</td></tr> </table> <a class="btn pull-right btn-small clear-register">Reset Register</a>' RAM_TABLE = '<div class="ram-options"> <input type="checkbox" name="ramautojump" id="ramautojump">Autojump to last modification</input> </div> <div class="ram-jump-to"> <div class="pre-input">Jump To: </div> <div class="input-right"><input type="text" placeholder="Address" id="ram-addr"></text></div> </div> <table class="table table-condensed" id="ram-table"> <tr><th class="first-col-ram">Address</th><th>Value</th></tr> <tr class="m16-ram-0"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-1"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-2"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-3"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-4"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-5"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-6"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-7"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-8"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-9"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-10"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-11"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-12"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-13"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-14"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> <tr class="m16-ram-15"><td><span>0x0000</span><span>0000000000000000</span></td><td>0000000000000000</td></tr> </table> <a class="btn pull-right btn-small clear-ram">Clear Ram</a>' BREAKPOINTS_TABLE = '<div>Click on the gutter to toggle Breakpoints.</div> <table class="table table-condensed" id="breakpoints-table"> <tr><th class="first-col-breakpoints">Line</th><th>Content</th><th class="last-col-breakpoints"></th></tr> <tr><td></td><td></td><td></td></tr> </table> <a class="btn pull-right btn-small rm-breakpoints">Remove all</a>' EMPTY_REGISTER = ({ "0": 0, "1": 1, "-1": -1, PC: 0, R0: 0, R1: 0, R2: 0, R3: 0, R4: 0, R5: 0, R6: 0, R7: 0, R8: 0, R9: 0, R10: 0, AC: 0, MBR: 0, MAR: 0 }) # only for 16bit numbers! toDecimal = (inp) -> return ((if (inp & (1 << 15)) > 0 then 0xffff << 16 else 0) | inp).toString() toBin = (inp) -> return (1 << 16 | (inp & 0xffff)).toString(2).slice(1) toHex = (inp) -> hex = (Number(inp) & 0xffff).toString(16) return "0x" + ("0000".substr(0, 4 - hex.length)) + hex.toUpperCase(); toHex2 = (inp) -> hex = ((Number(inp) & 0xffffffff) >>> 0).toString(16) return "0x" + ("00000000".substr(0, 8 - hex.length)) + hex.toUpperCase(); class EmulatorMain constructor: -> @code = window.cmCode = CodeMirror.fromTextArea(document.getElementById('code'), mode: 'micro16', tabSize: 4, smartIndent: false, lineNumbers: true, lineWrapping: false, firstLineNumber: 0 gutters:["breakpoints", "currentline", "CodeMirror-linenumbers"]) @asm = CodeMirror.fromTextArea(document.getElementById('out'), mode: 'none', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, firstLineNumber: 0) reinit: -> @parser = new Parser() @mic = null @convertFunc = null @updateConvertFunc("binary") @breakpoints = {} @lastBreak = -1 @isDone = false @userRegister = $.extend({}, EMPTY_REGISTER) @lastRegister = $.extend({}, EMPTY_REGISTER) @lastFlags = {"N" : 0, "Z": 0} @userRam = new Array(Math.pow(2, 16)) for element, i in @userRam @userRam[i] = 0 @ramStartPos = 0 @lastErrorLine = -1 @code.on("change", (cm, change) => @parser = new Parser() $("#run").removeAttr("disabled") $("#step").removeAttr("disabled") $("#pause").removeAttr("disabled") $("#reset").removeAttr("disabled") $(".status-text").text("Stopped") $(".status-text").css("color", "green") if @lastErrorLine >= 0 @asm.removeLineClass(@lastErrorLine, "background") try @parser.parse @code.getValue() catch error if error.name != "SyntaxError" then throw error #console.log error $("#run").attr("disabled", "disabled") $("#step").attr("disabled", "disabled") $("#pause").attr("disabled", "disabled") $("#reset").attr("disabled", "disabled") $(".status-text").text(error.message + (if error.line != undefined then " | At line: " + error.line else "")) $(".status-text").css("color", "red") @lastErrorLine = error.line #if error.line? # @asm.addLineClass(error.line, "background", "code-error-bg") return if @code.getValue() $("#share").val(location.href.replace(/#.*$/, "") + "#&inp=" + $.base64("btoa", @code.getValue())) @setValueAsm() @code.clearGutter("currentline") if change.text.length > 1 then @updateBreakpointLines() @makeMic() ) @code.on("gutterClick", (cm, n) => info = cm.lineInfo(n) marker = document.createElement("div"); marker.innerHTML = "&bull;"; marker.className = "breakpoint"; cm.setGutterMarker(n, "breakpoints", if info.gutterMarkers?.breakpoints then null else marker); @updateBreakpointLines() ) $("#step").click => @mic.step() if !@mic.isFinished() then $(".status-text").text("Paused") $("#reset").click => @code.setGutterMarker((if @mic? then @mic.addr else 0), "currentline", null) @mic.pause() @makeMic() @updateRegistersRam() $("#run").click => @mic.run() if not @isDone $("#run").attr("disabled", "disabled") $("#step").attr("disabled", "disabled") $("#pause").removeAttr("disabled") $(".status-text").text("Running") $("#pause").click => @mic.pause() $("#pause").attr("disabled", "disabled") $("#step").removeAttr("disabled") $("#run").removeAttr("disabled") $(".status-text").text("Paused" + if @breakpoints[@mic.addr] then " (Breakpoint)" else "") $("#clockSpeed").keyup => value = parseInt($("#clockSpeed").val()) @mic.setSpeed(if value then value else 1) $("#clockSpeed").change => value = parseInt($("#clockSpeed").val()) @mic.setSpeed(if value then value else 1) @visible = "register" $(".btn-register").click => $(".btn-register").parent().parent().find(".active").removeClass("active") $(".btn-register").parent().addClass("active") @visible = "register" $("#info").children().remove() $("#info").append(REGISTER_TABLE) @updateRegistersRam() $("#reg-table tbody tr:gt(3)").dblclick (event) => Jregister = $("td:nth-child(2)", $(event.target).parent()) register = Jregister.attr("class").match(/\w+$/) Jregister.text("") inp = $('<input type="text" data-toggle="tooltip" class="inj-reg"></input>') .css("margin", "0") .css("padding", "0") .css("height", Jregister.height()-2 + "px") .css("width", "150px") .attr("title", "Invalid Input. Correct Unit?") .data({register: register}) .appendTo(Jregister) inp.keypress (event) => if event.which == 13 then Jregister.click() #inp.tooltip() $("#reg-table tbody tr:gt(3)").click (event) => Jregister = $("td:nth-child(2)", $(event.target).parent()) inp = Jregister.find("input") register = $("td:nth-child(1)", $(event.target).parent()).text() text = inp.val() value = switch when not text then 0 when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(value) inp.tooltip() inp.tooltip("show") setTimeout((() => inp.tooltip("destroy")), 1100) return @userRegister[register] = value reg = @userRegister if @mic @mic.vm.register[register] = value reg = @mic.vm.register Jregister.text(@convertFunc reg[register]) $(".clear-register").click => @userRegister = $.extend({}, EMPTY_REGISTER) @updateRegistersRam() $(".btn-ram").click => $(".btn-ram").parent().parent().find(".active").removeClass("active") $(".btn-ram").parent().addClass("active") @visible = "ram" $("#info").children().remove() $("#info").append(RAM_TABLE) @updateRegistersRam() $("#ram-addr").keyup => text = $("#ram-addr").val() @ramStartPos = switch when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(@ramStartPos) and @ramStartPos? @ramStartPos = 0 @updateRegistersRam() $("#ram-table tbody tr:gt(0)").dblclick (event) => Jram = $("td:nth-child(2)", $(event.target).parent()) ramcol = Jram.parent().attr("class").match(/\w+$/) Jram.text("") inp = $('<input type="text" data-toggle="tooltip" class="inj-reg"></input>') .css("margin", "0") .css("padding", "0") .css("height", Jram.height()-2 + "px") .css("width", "150px") .attr("title", "Invalid Input. Correct Unit?") .data({ram: ramcol}) .appendTo(Jram) inp.keypress (event) => if event.which == 13 then Jram.click() $("#ram-table tbody tr:gt(0)").click (event) => Jram = $("td:nth-child(2)", $(event.target).parent()) inp = Jram.find("input") ramAddr = $("td:nth-child(1) span:nth-child(1)", $(event.target).parent()).text() ramAddr = parseInt(ramAddr, 16) text = inp.val() value = switch when not text then 0 when text.length > 2 and text[0] == "0" and text[1] == "x" then parseInt(text, 16) & 0xffff when @unitMode == "decimal" then parseInt(text, 10) & 0xffff when @unitMode == "hexadecimal" then parseInt(text, 16) & 0xffff when @unitMode == "binary" and not /[01]+/.test(text) then NaN else parseInt(text, 2) & 0xffff if isNaN(value) inp.tooltip() inp.tooltip("show") setTimeout((() => inp.tooltip("destroy")), 1100) return @userRam[ramAddr] = value ram = @userRam if @mic @mic.vm.ram.ram[ramAddr] = value ram = @mic.vm.ram.ram Jram.text(@convertFunc ram[ramAddr]) $(".clear-ram").click => for element, i in @userRam @userRam[i] = 0 @updateRegistersRam() $(".btn-breakpoints").click => $(".btn-breakpoints").parent().parent().find(".active").removeClass("active") $(".btn-breakpoints").parent().addClass("active") @visible = "breakpoints" $("#info").children().remove() $("#info").append(BREAKPOINTS_TABLE) @updateRegistersRam() $(".rm-breakpoints").click => @breakpoints = {} @code.clearGutter("breakpoints") @updateBreakpointLines() $(".load-example").click => $("#aboutModal").modal('hide') @code.setValue($.base64('atob', EXAMPLE_CODE)) # tab which is open by default $(".btn-register").click() $(".unit-binary").click => @updateConvertFunc "binary" @updateRegistersRam() $(".unit-decimal").click => @updateConvertFunc "decimal" @updateRegistersRam() $(".unit-hexadecimal").click => @updateConvertFunc "hexadecimal" @updateRegistersRam() inp = HashSearch.get("inp") if inp then @code.setValue($.base64("atob", inp)) HashSearch.remove("inp") @code.setValue(@code.getValue()) # trigger change makeMic: -> @mic = null @updateRegistersRam() @mic = @parser.makeMic() @mic.vm.register = $.extend({}, @userRegister) @mic.vm.ram.ram = @userRam.slice() @mic.events.on("step", => if @breakpoints[@mic.addr] and @mic.clock.started and @lastBreak != @mic.addr @lastBreak = @mic.addr $("#pause").click() return @lastBreak = -1 @code.setGutterMarker(@mic.addr, "currentline", null) ) @mic.events.on("stepped", => @updateRegistersRam()) @mic.events.on("stop", => @isDone = true $("#step").attr("disabled", "disabled") $("#run").attr("disabled", "disabled") $("#pause").attr("disabled", "disabled") $(".status-text").text("Finished") ) @mic.setSpeed(parseInt($("#clockSpeed").val()) or 1) $("#step").removeAttr("disabled") $("#run").removeAttr("disabled") $("#pause").removeAttr("disabled") $("#pause").attr("disabled", "disabled") $(".status-text").text("Stopped") @mic.vm.ram.events.on("write", (pos, data) => if $("input[name=ramautojump]").prop("checked") then @ramStartPos = pos @updateRegistersRam() ) @mic.vm.ram.events.on("read", (pos) => @updateRegistersRam()) updateRegistersRam: -> switch @visible when "register" then @updateRegisters() when "ram" then @updateRam() when "breakpoints" then @updateBreakpoints() @code.clearGutter("currentline") @setGutterMark(if @mic? then @mic.addr else 0) updateRegisters: -> registers = if @mic? then @mic.vm.register else @userRegister flags = if @mic? then @mic.vm.flags else @lastFlags for own key, value of registers j = $(".m16-reg-key-" + key) j.parent().removeClass("info") if @lastRegister[key] != value then j.parent().addClass("info") j.text(@convertFunc value) for f in ["N", "Z"] j = $(".m16-flag-" + f.toLowerCase()) j.parent().removeClass("info") if @lastFlags[f] != flags[f] then j.parent().addClass("info"); j.text(@convertFunc flags[f]) @lastRegister = registers @lastFlags = flags updateRam: -> ram = if @mic? then @mic.vm.ram else {get: (i) => @userRam[i]} for i in [0..15] ii = @ramStartPos+i s = ".m16-ram-" + i #rotate! $(s + " td:last-child").text(@convertFunc ram.get(parseInt(toDecimal(toBin(ii)), 2))) $(s + " td:first-child span:nth-child(1)") .text(toHex(ii)) $(s + " td:first-child span:nth-child(2)") .text(toBin(ii)) updateBreakpointLines: -> @breakpoints = {} @code.eachLine (handle) => info = @code.lineInfo(handle) line = info.line if info.gutterMarkers?.breakpoints @breakpoints[line] = true return if @visible == "breakpoints" @updateBreakpoints() updateBreakpoints: -> $("#breakpoints-table tbody tr:gt(1)").remove() for key, value of @breakpoints $("<tr></tr>") .append($("<td></td>").text(key)) .append($("<td></td>").text(@code.getLineHandle(key).text)) .append($("<td></td>") .html('<i class="icon-remove"></i>') .click => @code.setGutterMarker(@code.getLineHandle(key), "breakpoints", null) @updateBreakpointLines() ) .appendTo("#breakpoints-table tbody") setGutterMark: (addr) -> element = document.createElement("div") element.innerHTML = "&rarr;" @code.setGutterMarker((if addr? then addr else @mic.attr), "currentline", element) updateConvertFunc: (unit) -> $(".unit-binary").parent().parent().find("i").remove() @unitMode = unit switch unit when "decimal" $(".unit-decimal").html('Decimal <i class="icon-ok">') @convertFunc = toDecimal when "hexadecimal" $(".unit-hexadecimal").html('Hexadecimal <i class="icon-ok">') @convertFunc = (inp) -> return toHex(toDecimal(inp)) else $(".unit-binary").html('Binary <i class="icon-ok">') @convertFunc = toBin @unitMode = "binary" @setValueAsm() setValueAsm: -> @asm.setValue($.map(@parser.getFormattedIns("").replace(/\s+$/, "").split("\n"), (x, i) => switch @unitMode when x == undefined or x == null or x.length == 0 then return "" when "decimal" then return x when "hexadecimal" then return toHex2(parseInt(x, 2)) else return x ).join("\n").replace(/\s+$/, "")) class DisassemblerMain constructor: -> @disin = CodeMirror.fromTextArea(document.getElementById('disin'), mode: 'none', tabSize: 4, smartIndent: false, lineNumbers: true, lineWrapping: false, firstLineNumber: 0 ) @disout = CodeMirror.fromTextArea(document.getElementById('disout'), mode: 'micro16', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, gutter: false, firstLineNumber: 0 ) @disinhex = CodeMirror.fromTextArea(document.getElementById('disinhex'), mode: 'none', smartIndent: false, lineNumbers: true, lineWrapping: false, readOnly: true, gutter: false, firstLineNumber: 0 ) disassembler = new Disassembler() @disin.on("change", (cm, change) => $(".status-text").text("Everything fine!") $(".status-text").css("color", "green") out = null try out = disassembler.disassembleLines(@disin.getValue()) catch error if error.name != "DisassemblerError" then throw error @disout.setValue("") $(".status-text").text(error.message + (if error.line != undefined then " | At line: " + error.line else "")) $(".status-text").css("color", "red") return if @disin.getValue() $("#share").val(location.href.replace(/#.*$/, "") + "#disasm&inp=" + $.base64("btoa", @disin.getValue())) @disout.setValue out["dis"].join("\n") @disinhex.setValue $.map(out["ins"], (x, i) -> toHex2(x)).join("\n") ) reinit: -> $(".load-emu").click => $("#switchEmu").click() window.cmCode.setValue(@disout.getValue()) inp = HashSearch.get("inp") if inp then @disin.setValue($.base64("atob", inp)) HashSearch.remove("inp") @disin.setValue(@disin.getValue()) # trigger change # main entry point $ -> HashSearch.load() emulator = $("#outer").children() disassembler = $(DISASM_HTML) current = null cls = {} resize = -> height = $(window).height() - 120 height5 = height / 5 $(".CodeMirror").height(height) $("#register").height(height5 * 3) $("#ram").height(height5 * 2) $("#disin").height(height5 * 3) $("#disout").height(height5 * 2) $("#switchDis").click => if current == "disassembler" then return else current = "disassembler" if not HashSearch.keyExists("disasm") then HashSearch.set("disasm") $("#switchDis").parent().parent().find(".active").removeClass("active") $("#switchDis").parent().addClass("active") $("#outer").children().remove() $("#outer").append(disassembler) if not cls[current] then cls[current] = new DisassemblerMain() cls[current].reinit() resize() $("#switchEmu").click => if current == "emulator" then return else current = "emulator" HashSearch.remove("disasm") $("#switchEmu").parent().parent().find(".active").removeClass("active") $("#switchEmu").parent().addClass("active") $("#outer").children().remove() $("#outer").append(emulator) if not cls[current] then cls[current] = new EmulatorMain() cls[current].reinit() resize() if HashSearch.keyExists("disasm") $("#switchDis").click() else $("#switchEmu").click() $(window).resize resize resize()
[ { "context": "is, those are lost when bot exits.\n#\n# Author:\n# Jin Araki <jinzam.rock@gmail.com>\n\nclass Track\n\n construct", "end": 410, "score": 0.9997851848602295, "start": 401, "tag": "NAME", "value": "Jin Araki" }, { "context": "e lost when bot exits.\n#\n# Author:\n# Jin Araki <jinzam.rock@gmail.com>\n\nclass Track\n\n constructor: (track) ->\n {@pr", "end": 433, "score": 0.9999350309371948, "start": 412, "tag": "EMAIL", "value": "jinzam.rock@gmail.com" } ]
scripts/tt.coffee
jinzam/hubot-tt
0
# Description: # Personal Time Tracker # # Commands: # hubot tt start <project>/<task> - Start tracking on project/task # hubot tt stop - Stop current tracking # hubot tt report - Report tracking data of you # hubot tt reset - Reset database (Clear all trackings of you) # # Notes: # All tracking data are stored only in memory. # That is, those are lost when bot exits. # # Author: # Jin Araki <jinzam.rock@gmail.com> class Track constructor: (track) -> {@project, @task, @timeIn, @timeOut, @timeHours} = track @project ?= 'no data' @task ?= 'no data' @timeIn ?= null @timeOut ?= null @timeHours ?= 0 @taskId = "#{@project}/#{@task}" class TimeTracker constructor: (@robot) -> @isTracking = false @db = [] start: (now, track) -> @stop now if @isTracking @isTracking = true track.timeIn = now @db.push(track) stop: (now) -> if @isTracking t = @db[@db.length - 1] t.timeOut = now t.timeHours = (now.getTime() - t.timeIn.getTime()) / 1000 / 60 / 60 @isTracking = false list: (opt) -> if opt.filterBy is 'today' now = new Date today = now.toDateString() list = (t for t in @db when t.timeIn.toDateString() is today) else list = @db[..] if opt.groupBy is 'task' taskIds = new Set(t.taskId for t in @db) merged_list = [] taskIds.forEach (taskId) -> track = list.filter (t) -> t.taskId is taskId .reduce (x, y) -> x.project = y.project x.task = y.task x.timeHours ?= 0 x.timeHours += y.timeHours x , {} merged_track = new Track track merged_list.push(merged_track) list = merged_list list reset: -> @isTracking = false @db = [] module.exports = (robot) -> # {'username': [Track, ...], ...} time_tracker_db = {} # Start tracking robot.respond /tt start (.+)\/(.+)/i, (res) -> username = res.message.user.name if time_tracker_db[username]? tt = time_tracker_db[username] else tt = time_tracker_db[username] = new TimeTracker robot project = res.match[1] task = res.match[2] track = new Track project: project, task: task now = new Date tt.start now, track res.send "#{username} started #{project}/#{task}" # Stop tracking robot.respond /tt stop/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] tt?.stop new Date res.send "#{username} stopped tracking" # Report tracking data robot.respond /tt report/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] list = tt?.list filterBy: 'today', groupBy: 'task' or [] md_manhour = list.map (t) -> "|#{t.project}|#{t.task}|#{t.timeHours.toFixed(2)}|" .join '\n' list = tt?.list filterBy: 'today' or [] md_timesheet = list.map (t) -> "|#{t.timeIn.toLocaleTimeString()}|#{t.timeOut?.toLocaleTimeString() or ''}|#{t.timeHours.toFixed(2)}|#{t.project}|#{t.task}|" .join '\n' md_contents = """ ### #{new Date().toDateString()} -- #{username} #### Man-hour | Project | Task | Hours | | ------- | ---- | ----- | #{md_manhour} #### Time-sheet | In | Out | Hours | Project | Task | | -- | --- | ----- | ------- |----- | #{md_timesheet} """ res.send md_contents # Reset database robot.respond /tt reset/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] tt?.reset() res.send "Clear tracking data of #{username}"
168343
# Description: # Personal Time Tracker # # Commands: # hubot tt start <project>/<task> - Start tracking on project/task # hubot tt stop - Stop current tracking # hubot tt report - Report tracking data of you # hubot tt reset - Reset database (Clear all trackings of you) # # Notes: # All tracking data are stored only in memory. # That is, those are lost when bot exits. # # Author: # <NAME> <<EMAIL>> class Track constructor: (track) -> {@project, @task, @timeIn, @timeOut, @timeHours} = track @project ?= 'no data' @task ?= 'no data' @timeIn ?= null @timeOut ?= null @timeHours ?= 0 @taskId = "#{@project}/#{@task}" class TimeTracker constructor: (@robot) -> @isTracking = false @db = [] start: (now, track) -> @stop now if @isTracking @isTracking = true track.timeIn = now @db.push(track) stop: (now) -> if @isTracking t = @db[@db.length - 1] t.timeOut = now t.timeHours = (now.getTime() - t.timeIn.getTime()) / 1000 / 60 / 60 @isTracking = false list: (opt) -> if opt.filterBy is 'today' now = new Date today = now.toDateString() list = (t for t in @db when t.timeIn.toDateString() is today) else list = @db[..] if opt.groupBy is 'task' taskIds = new Set(t.taskId for t in @db) merged_list = [] taskIds.forEach (taskId) -> track = list.filter (t) -> t.taskId is taskId .reduce (x, y) -> x.project = y.project x.task = y.task x.timeHours ?= 0 x.timeHours += y.timeHours x , {} merged_track = new Track track merged_list.push(merged_track) list = merged_list list reset: -> @isTracking = false @db = [] module.exports = (robot) -> # {'username': [Track, ...], ...} time_tracker_db = {} # Start tracking robot.respond /tt start (.+)\/(.+)/i, (res) -> username = res.message.user.name if time_tracker_db[username]? tt = time_tracker_db[username] else tt = time_tracker_db[username] = new TimeTracker robot project = res.match[1] task = res.match[2] track = new Track project: project, task: task now = new Date tt.start now, track res.send "#{username} started #{project}/#{task}" # Stop tracking robot.respond /tt stop/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] tt?.stop new Date res.send "#{username} stopped tracking" # Report tracking data robot.respond /tt report/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] list = tt?.list filterBy: 'today', groupBy: 'task' or [] md_manhour = list.map (t) -> "|#{t.project}|#{t.task}|#{t.timeHours.toFixed(2)}|" .join '\n' list = tt?.list filterBy: 'today' or [] md_timesheet = list.map (t) -> "|#{t.timeIn.toLocaleTimeString()}|#{t.timeOut?.toLocaleTimeString() or ''}|#{t.timeHours.toFixed(2)}|#{t.project}|#{t.task}|" .join '\n' md_contents = """ ### #{new Date().toDateString()} -- #{username} #### Man-hour | Project | Task | Hours | | ------- | ---- | ----- | #{md_manhour} #### Time-sheet | In | Out | Hours | Project | Task | | -- | --- | ----- | ------- |----- | #{md_timesheet} """ res.send md_contents # Reset database robot.respond /tt reset/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] tt?.reset() res.send "Clear tracking data of #{username}"
true
# Description: # Personal Time Tracker # # Commands: # hubot tt start <project>/<task> - Start tracking on project/task # hubot tt stop - Stop current tracking # hubot tt report - Report tracking data of you # hubot tt reset - Reset database (Clear all trackings of you) # # Notes: # All tracking data are stored only in memory. # That is, those are lost when bot exits. # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> class Track constructor: (track) -> {@project, @task, @timeIn, @timeOut, @timeHours} = track @project ?= 'no data' @task ?= 'no data' @timeIn ?= null @timeOut ?= null @timeHours ?= 0 @taskId = "#{@project}/#{@task}" class TimeTracker constructor: (@robot) -> @isTracking = false @db = [] start: (now, track) -> @stop now if @isTracking @isTracking = true track.timeIn = now @db.push(track) stop: (now) -> if @isTracking t = @db[@db.length - 1] t.timeOut = now t.timeHours = (now.getTime() - t.timeIn.getTime()) / 1000 / 60 / 60 @isTracking = false list: (opt) -> if opt.filterBy is 'today' now = new Date today = now.toDateString() list = (t for t in @db when t.timeIn.toDateString() is today) else list = @db[..] if opt.groupBy is 'task' taskIds = new Set(t.taskId for t in @db) merged_list = [] taskIds.forEach (taskId) -> track = list.filter (t) -> t.taskId is taskId .reduce (x, y) -> x.project = y.project x.task = y.task x.timeHours ?= 0 x.timeHours += y.timeHours x , {} merged_track = new Track track merged_list.push(merged_track) list = merged_list list reset: -> @isTracking = false @db = [] module.exports = (robot) -> # {'username': [Track, ...], ...} time_tracker_db = {} # Start tracking robot.respond /tt start (.+)\/(.+)/i, (res) -> username = res.message.user.name if time_tracker_db[username]? tt = time_tracker_db[username] else tt = time_tracker_db[username] = new TimeTracker robot project = res.match[1] task = res.match[2] track = new Track project: project, task: task now = new Date tt.start now, track res.send "#{username} started #{project}/#{task}" # Stop tracking robot.respond /tt stop/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] tt?.stop new Date res.send "#{username} stopped tracking" # Report tracking data robot.respond /tt report/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] list = tt?.list filterBy: 'today', groupBy: 'task' or [] md_manhour = list.map (t) -> "|#{t.project}|#{t.task}|#{t.timeHours.toFixed(2)}|" .join '\n' list = tt?.list filterBy: 'today' or [] md_timesheet = list.map (t) -> "|#{t.timeIn.toLocaleTimeString()}|#{t.timeOut?.toLocaleTimeString() or ''}|#{t.timeHours.toFixed(2)}|#{t.project}|#{t.task}|" .join '\n' md_contents = """ ### #{new Date().toDateString()} -- #{username} #### Man-hour | Project | Task | Hours | | ------- | ---- | ----- | #{md_manhour} #### Time-sheet | In | Out | Hours | Project | Task | | -- | --- | ----- | ------- |----- | #{md_timesheet} """ res.send md_contents # Reset database robot.respond /tt reset/i, (res) -> username = res.message.user.name tt = time_tracker_db[username] tt?.reset() res.send "Clear tracking data of #{username}"
[ { "context": "#*\n# @fileoverview Detects unused styles\n# @author Tom Hastjarjanto\n###\n\n'use strict'\n\nComponents = require '../util/", "end": 69, "score": 0.9998912811279297, "start": 53, "tag": "NAME", "value": "Tom Hastjarjanto" } ]
src/rules/no-unused-styles.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Detects unused styles # @author Tom Hastjarjanto ### 'use strict' Components = require '../util/react/Components' styleSheet = require '../util/react-native/stylesheet' # styleSheet = require 'eslint-plugin-react-native/lib/util/stylesheet' {StyleSheets, astHelpers} = styleSheet module.exports = Components.detect (context, components) -> styleSheets = new StyleSheets() styleReferences = new Set() reportUnusedStyles = (unusedStyles) -> for own key, styles of unusedStyles # eslint-disable-next-line coffee/no-loop-func styles.forEach (node) -> message = ['Unused style detected: ', key, '.', node.key.name].join '' context.report node, message checkAssignment = (node) -> if astHelpers.isStyleSheetDeclaration node styleSheetName = astHelpers.getStyleSheetName node styles = astHelpers.getStyleDeclarations node styleSheets.add styleSheetName, styles MemberExpression: (node) -> styleRef = astHelpers.getPotentialStyleReferenceFromMemberExpression node styleReferences.add styleRef if styleRef VariableDeclarator: checkAssignment AssignmentExpression: checkAssignment 'Program:exit': -> list = components.list() if Object.keys(list).length > 0 styleReferences.forEach (reference) -> styleSheets.markAsUsed reference reportUnusedStyles styleSheets.getUnusedReferences() module.exports.schema = []
108037
###* # @fileoverview Detects unused styles # @author <NAME> ### 'use strict' Components = require '../util/react/Components' styleSheet = require '../util/react-native/stylesheet' # styleSheet = require 'eslint-plugin-react-native/lib/util/stylesheet' {StyleSheets, astHelpers} = styleSheet module.exports = Components.detect (context, components) -> styleSheets = new StyleSheets() styleReferences = new Set() reportUnusedStyles = (unusedStyles) -> for own key, styles of unusedStyles # eslint-disable-next-line coffee/no-loop-func styles.forEach (node) -> message = ['Unused style detected: ', key, '.', node.key.name].join '' context.report node, message checkAssignment = (node) -> if astHelpers.isStyleSheetDeclaration node styleSheetName = astHelpers.getStyleSheetName node styles = astHelpers.getStyleDeclarations node styleSheets.add styleSheetName, styles MemberExpression: (node) -> styleRef = astHelpers.getPotentialStyleReferenceFromMemberExpression node styleReferences.add styleRef if styleRef VariableDeclarator: checkAssignment AssignmentExpression: checkAssignment 'Program:exit': -> list = components.list() if Object.keys(list).length > 0 styleReferences.forEach (reference) -> styleSheets.markAsUsed reference reportUnusedStyles styleSheets.getUnusedReferences() module.exports.schema = []
true
###* # @fileoverview Detects unused styles # @author PI:NAME:<NAME>END_PI ### 'use strict' Components = require '../util/react/Components' styleSheet = require '../util/react-native/stylesheet' # styleSheet = require 'eslint-plugin-react-native/lib/util/stylesheet' {StyleSheets, astHelpers} = styleSheet module.exports = Components.detect (context, components) -> styleSheets = new StyleSheets() styleReferences = new Set() reportUnusedStyles = (unusedStyles) -> for own key, styles of unusedStyles # eslint-disable-next-line coffee/no-loop-func styles.forEach (node) -> message = ['Unused style detected: ', key, '.', node.key.name].join '' context.report node, message checkAssignment = (node) -> if astHelpers.isStyleSheetDeclaration node styleSheetName = astHelpers.getStyleSheetName node styles = astHelpers.getStyleDeclarations node styleSheets.add styleSheetName, styles MemberExpression: (node) -> styleRef = astHelpers.getPotentialStyleReferenceFromMemberExpression node styleReferences.add styleRef if styleRef VariableDeclarator: checkAssignment AssignmentExpression: checkAssignment 'Program:exit': -> list = components.list() if Object.keys(list).length > 0 styleReferences.forEach (reference) -> styleSheets.markAsUsed reference reportUnusedStyles styleSheets.getUnusedReferences() module.exports.schema = []
[ { "context": "eLeap extends Skill\n target: TARGET_DIR8\n key: 'savage_leap'\n name: 'savage leap'\n mp: 5\n cooldown: 10\n\n ", "end": 72, "score": 0.8396689295768738, "start": 61, "tag": "KEY", "value": "savage_leap" } ]
js/skills/savage_leap.coffee
ktchernov/7drl-lion.github.io
27
class SavageLeap extends Skill target: TARGET_DIR8 key: 'savage_leap' name: 'savage leap' mp: 5 cooldown: 10 run: (dir) -> [i, j] = @state.get_pos @id [x, y] = @state.pos_in_direction i, j, dir, 3 return if @state.is_blocked(x, y) adjacent = @state.get_all_adjacent_pos x, y has_enemy = [] _.each adjacent, (pos) => has_enemy.push pos if @state.is_creature pos... return if has_enemy.length == 0 actor_short = @state.get_short_description @id @state.msg @id, "You leap into the fray!" @state.shout_by @id, "#{_.str.capitalize(actor_short)} leaps into the fray!" @state.set_pos @id, x, y _.each has_enemy, (pos) => dir = @state.general_direction @id, pos... @execute_action 'attack', dir, mod: 0.2, flavor: "stomp" true register_skill 'savage_leap', SavageLeap
11809
class SavageLeap extends Skill target: TARGET_DIR8 key: '<KEY>' name: 'savage leap' mp: 5 cooldown: 10 run: (dir) -> [i, j] = @state.get_pos @id [x, y] = @state.pos_in_direction i, j, dir, 3 return if @state.is_blocked(x, y) adjacent = @state.get_all_adjacent_pos x, y has_enemy = [] _.each adjacent, (pos) => has_enemy.push pos if @state.is_creature pos... return if has_enemy.length == 0 actor_short = @state.get_short_description @id @state.msg @id, "You leap into the fray!" @state.shout_by @id, "#{_.str.capitalize(actor_short)} leaps into the fray!" @state.set_pos @id, x, y _.each has_enemy, (pos) => dir = @state.general_direction @id, pos... @execute_action 'attack', dir, mod: 0.2, flavor: "stomp" true register_skill 'savage_leap', SavageLeap
true
class SavageLeap extends Skill target: TARGET_DIR8 key: 'PI:KEY:<KEY>END_PI' name: 'savage leap' mp: 5 cooldown: 10 run: (dir) -> [i, j] = @state.get_pos @id [x, y] = @state.pos_in_direction i, j, dir, 3 return if @state.is_blocked(x, y) adjacent = @state.get_all_adjacent_pos x, y has_enemy = [] _.each adjacent, (pos) => has_enemy.push pos if @state.is_creature pos... return if has_enemy.length == 0 actor_short = @state.get_short_description @id @state.msg @id, "You leap into the fray!" @state.shout_by @id, "#{_.str.capitalize(actor_short)} leaps into the fray!" @state.set_pos @id, x, y _.each has_enemy, (pos) => dir = @state.general_direction @id, pos... @execute_action 'attack', dir, mod: 0.2, flavor: "stomp" true register_skill 'savage_leap', SavageLeap
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9986518025398254, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-zlib-from-multiple-huge-gzip.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test unzipping a file that was created by concatenating multiple gzip # streams. getRandomLetter = -> (Math.random() * (122 - 97)) + 97 generateHugeStream = -> buffer = new Buffer(HUGE) i = 0 while i < HUGE buffer.writeUInt8 getRandomLetter(), i i++ buffer.copy originalBuffer, originalOffset originalOffset += HUGE buffer gzipAppend = (data) -> data.copy gzipBuffer, gzipOffset gzipOffset += data.length return writeGzipStream = (text, cb) -> gzip = zlib.createGzip() gzip.on "data", gzipAppend gzip.write text, -> gzip.flush -> gzip.end -> cb() return return return return common = require("../common") assert = require("assert") zlib = require("zlib") util = require("util") HUGE = 64 * 1024 originalBuffer = new Buffer(3 * HUGE) originalOffset = 0 gzipBuffer = new Buffer(3 * HUGE) gzipOffset = 0 writeGzipStream generateHugeStream(), -> writeGzipStream generateHugeStream(), -> writeGzipStream generateHugeStream(), -> gunzip = zlib.createGunzip() gunzippedData = new Buffer(3 * HUGE) gunzippedOffset = 0 gunzip.on "data", (data) -> data.copy gunzippedData, gunzippedOffset gunzippedOffset += data.length return gunzip.on "end", -> gunzippedStr = gunzippedData.toString("utf8", 0, gunzippedOffset) originalStr = originalBuffer.toString("utf8", 0, 3 * HUGE) assert.equal gunzippedStr, originalStr return gunzip.write gzipBuffer.slice(0, gzipOffset), "binary", -> gunzip.end() return return return return
11914
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test unzipping a file that was created by concatenating multiple gzip # streams. getRandomLetter = -> (Math.random() * (122 - 97)) + 97 generateHugeStream = -> buffer = new Buffer(HUGE) i = 0 while i < HUGE buffer.writeUInt8 getRandomLetter(), i i++ buffer.copy originalBuffer, originalOffset originalOffset += HUGE buffer gzipAppend = (data) -> data.copy gzipBuffer, gzipOffset gzipOffset += data.length return writeGzipStream = (text, cb) -> gzip = zlib.createGzip() gzip.on "data", gzipAppend gzip.write text, -> gzip.flush -> gzip.end -> cb() return return return return common = require("../common") assert = require("assert") zlib = require("zlib") util = require("util") HUGE = 64 * 1024 originalBuffer = new Buffer(3 * HUGE) originalOffset = 0 gzipBuffer = new Buffer(3 * HUGE) gzipOffset = 0 writeGzipStream generateHugeStream(), -> writeGzipStream generateHugeStream(), -> writeGzipStream generateHugeStream(), -> gunzip = zlib.createGunzip() gunzippedData = new Buffer(3 * HUGE) gunzippedOffset = 0 gunzip.on "data", (data) -> data.copy gunzippedData, gunzippedOffset gunzippedOffset += data.length return gunzip.on "end", -> gunzippedStr = gunzippedData.toString("utf8", 0, gunzippedOffset) originalStr = originalBuffer.toString("utf8", 0, 3 * HUGE) assert.equal gunzippedStr, originalStr return gunzip.write gzipBuffer.slice(0, gzipOffset), "binary", -> gunzip.end() return return return return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test unzipping a file that was created by concatenating multiple gzip # streams. getRandomLetter = -> (Math.random() * (122 - 97)) + 97 generateHugeStream = -> buffer = new Buffer(HUGE) i = 0 while i < HUGE buffer.writeUInt8 getRandomLetter(), i i++ buffer.copy originalBuffer, originalOffset originalOffset += HUGE buffer gzipAppend = (data) -> data.copy gzipBuffer, gzipOffset gzipOffset += data.length return writeGzipStream = (text, cb) -> gzip = zlib.createGzip() gzip.on "data", gzipAppend gzip.write text, -> gzip.flush -> gzip.end -> cb() return return return return common = require("../common") assert = require("assert") zlib = require("zlib") util = require("util") HUGE = 64 * 1024 originalBuffer = new Buffer(3 * HUGE) originalOffset = 0 gzipBuffer = new Buffer(3 * HUGE) gzipOffset = 0 writeGzipStream generateHugeStream(), -> writeGzipStream generateHugeStream(), -> writeGzipStream generateHugeStream(), -> gunzip = zlib.createGunzip() gunzippedData = new Buffer(3 * HUGE) gunzippedOffset = 0 gunzip.on "data", (data) -> data.copy gunzippedData, gunzippedOffset gunzippedOffset += data.length return gunzip.on "end", -> gunzippedStr = gunzippedData.toString("utf8", 0, gunzippedOffset) originalStr = originalBuffer.toString("utf8", 0, 3 * HUGE) assert.equal gunzippedStr, originalStr return gunzip.write gzipBuffer.slice(0, gzipOffset), "binary", -> gunzip.end() return return return return
[ { "context": " collection = new Collection\n title: 'First Todo'\n done: true\n\n view = new TodoLi", "end": 277, "score": 0.9286161065101624, "start": 272, "tag": "NAME", "value": "First" } ]
app/templates/seed/js/routers/todo-list.coffee
mmonto7/generator-thorax
22
define [ 'backbone' 'cs!collection' 'cs!views/root' 'cs!views/todo-list/index' ], (Backbone, Collection, RootView, TodoListIndexView) -> return Backbone.Router.extend routes: "": "index" index: -> collection = new Collection title: 'First Todo' done: true view = new TodoListIndexView {collection} RootView.getInstance().setView view
185127
define [ 'backbone' 'cs!collection' 'cs!views/root' 'cs!views/todo-list/index' ], (Backbone, Collection, RootView, TodoListIndexView) -> return Backbone.Router.extend routes: "": "index" index: -> collection = new Collection title: '<NAME> Todo' done: true view = new TodoListIndexView {collection} RootView.getInstance().setView view
true
define [ 'backbone' 'cs!collection' 'cs!views/root' 'cs!views/todo-list/index' ], (Backbone, Collection, RootView, TodoListIndexView) -> return Backbone.Router.extend routes: "": "index" index: -> collection = new Collection title: 'PI:NAME:<NAME>END_PI Todo' done: true view = new TodoListIndexView {collection} RootView.getInstance().setView view
[ { "context": " 0\n tasks\n\n createTask: =>\n task = {name: \"New task\", original_estimate: 0}\n Api.create_task gon.p", "end": 750, "score": 0.8769179582595825, "start": 742, "tag": "NAME", "value": "New task" } ]
app/assets/javascripts/models/tasks.js.coffee
dfraser74/sofreakingboring
17
class @TasksModel constructor: -> @tasks = [] @members = [] @selectableMembers = [] @subscribers = [] subscribe: (callback) -> @subscribers.push callback unsubscribe: (callback) -> @subscribers = @subscribers.filter (item) -> item isnt callback notify: -> subscriber() for subscriber in @subscribers loadTasks: -> Api.tasks gon.project_id, (tasks) => @tasks = tasks @notify() data = null getTasksTotal: -> @tasks.length getTasks: (filter = '', displayCompleted = true, sort = '', order = 'asc') -> tasks = @filterTasks(@tasks, filter, displayCompleted) tasks = @sortTasks(tasks, sort, order) if sort.length > 0 tasks createTask: => task = {name: "New task", original_estimate: 0} Api.create_task gon.project_id, task, (task) => @tasks.push task @notify() removeTasks: (tasks) -> @removeTask(task) for task in tasks @notify() addTask: (item) -> @tasks.push(item) updateTask: (item) -> task = @getTask(item.id) task.name = item.name task.description = item.description task.tag_list = item.tag_list task.assignee_id = item.assignee_id task.original_estimate = item.original_estimate task.remaining_estimate = item.remaining_estimate task.delta = item.delta Api.update_task gon.project_id, item.id, item, (task) => @getTask(task.id).updated_at = task.updated_at @notify() removeTask: (item) -> Api.delete_task gon.project_id, item.id index = @tasks.indexOf(item) @tasks.splice(index, 1) getTask: (id) -> found = @tasks.where id:id if found.length > 0 then found[0] else null getTaskAt: (index) -> @tasks[index] setTask: (tasks) -> @tasks = tasks filterTasks: (tasks, filter = '', displayCompleted = true) -> data = tasks if filter.length > 0 filter = filter.toLowerCase() filtered = [] for task in data addIt = task.code.toLowerCase().indexOf(filter) > -1 if !addIt addIt = task.name.toLowerCase().indexOf(filter) > -1 if !addIt tags = task.tag_list.split(',') for tag in tags tag = $.trim(tag) if tag.toLowerCase().indexOf(filter) > -1 addIt = true break if !addIt found = @members.where user_id:task.assignee_id addIt = found.length > 0 && found[0].username.toLowerCase().indexOf(filter) > -1 filtered.push(task) if addIt data = filtered if !displayCompleted filtered = [] for task in data if task.remaining_estimate > 0 or task.original_estimate == 0 filtered.push(task) data = filtered data sortTasks: (tasks, key, order) -> tasks.sort (a,b) -> m = if order == 'asc' then 1 else -1 return -1 * m if a[key] < b[key] return +1 * m if a[key] > b[key] return 0 loadMembers: (callback) -> Api.project_members gon.project_id, (members) => @members = members if gon.can_update_tasks @selectableMembers = members else found = @members.where user_id:gon.user_id @selectableMembers = found callback() findUsername: (user_id) -> found = @members.where user_id:user_id if found.length > 0 then found[0].username else null canChangeAssignee: (task) -> resu = false logged = task.work_logged if logged == 0 if gon.can_take_unassigned_task && !gon.can_update_tasks resu = task.assignee_id == "" or task.assignee_id == null or parseInt(task.assignee_id) == gon.user_id else resu = gon.can_update_tasks resu
7386
class @TasksModel constructor: -> @tasks = [] @members = [] @selectableMembers = [] @subscribers = [] subscribe: (callback) -> @subscribers.push callback unsubscribe: (callback) -> @subscribers = @subscribers.filter (item) -> item isnt callback notify: -> subscriber() for subscriber in @subscribers loadTasks: -> Api.tasks gon.project_id, (tasks) => @tasks = tasks @notify() data = null getTasksTotal: -> @tasks.length getTasks: (filter = '', displayCompleted = true, sort = '', order = 'asc') -> tasks = @filterTasks(@tasks, filter, displayCompleted) tasks = @sortTasks(tasks, sort, order) if sort.length > 0 tasks createTask: => task = {name: "<NAME>", original_estimate: 0} Api.create_task gon.project_id, task, (task) => @tasks.push task @notify() removeTasks: (tasks) -> @removeTask(task) for task in tasks @notify() addTask: (item) -> @tasks.push(item) updateTask: (item) -> task = @getTask(item.id) task.name = item.name task.description = item.description task.tag_list = item.tag_list task.assignee_id = item.assignee_id task.original_estimate = item.original_estimate task.remaining_estimate = item.remaining_estimate task.delta = item.delta Api.update_task gon.project_id, item.id, item, (task) => @getTask(task.id).updated_at = task.updated_at @notify() removeTask: (item) -> Api.delete_task gon.project_id, item.id index = @tasks.indexOf(item) @tasks.splice(index, 1) getTask: (id) -> found = @tasks.where id:id if found.length > 0 then found[0] else null getTaskAt: (index) -> @tasks[index] setTask: (tasks) -> @tasks = tasks filterTasks: (tasks, filter = '', displayCompleted = true) -> data = tasks if filter.length > 0 filter = filter.toLowerCase() filtered = [] for task in data addIt = task.code.toLowerCase().indexOf(filter) > -1 if !addIt addIt = task.name.toLowerCase().indexOf(filter) > -1 if !addIt tags = task.tag_list.split(',') for tag in tags tag = $.trim(tag) if tag.toLowerCase().indexOf(filter) > -1 addIt = true break if !addIt found = @members.where user_id:task.assignee_id addIt = found.length > 0 && found[0].username.toLowerCase().indexOf(filter) > -1 filtered.push(task) if addIt data = filtered if !displayCompleted filtered = [] for task in data if task.remaining_estimate > 0 or task.original_estimate == 0 filtered.push(task) data = filtered data sortTasks: (tasks, key, order) -> tasks.sort (a,b) -> m = if order == 'asc' then 1 else -1 return -1 * m if a[key] < b[key] return +1 * m if a[key] > b[key] return 0 loadMembers: (callback) -> Api.project_members gon.project_id, (members) => @members = members if gon.can_update_tasks @selectableMembers = members else found = @members.where user_id:gon.user_id @selectableMembers = found callback() findUsername: (user_id) -> found = @members.where user_id:user_id if found.length > 0 then found[0].username else null canChangeAssignee: (task) -> resu = false logged = task.work_logged if logged == 0 if gon.can_take_unassigned_task && !gon.can_update_tasks resu = task.assignee_id == "" or task.assignee_id == null or parseInt(task.assignee_id) == gon.user_id else resu = gon.can_update_tasks resu
true
class @TasksModel constructor: -> @tasks = [] @members = [] @selectableMembers = [] @subscribers = [] subscribe: (callback) -> @subscribers.push callback unsubscribe: (callback) -> @subscribers = @subscribers.filter (item) -> item isnt callback notify: -> subscriber() for subscriber in @subscribers loadTasks: -> Api.tasks gon.project_id, (tasks) => @tasks = tasks @notify() data = null getTasksTotal: -> @tasks.length getTasks: (filter = '', displayCompleted = true, sort = '', order = 'asc') -> tasks = @filterTasks(@tasks, filter, displayCompleted) tasks = @sortTasks(tasks, sort, order) if sort.length > 0 tasks createTask: => task = {name: "PI:NAME:<NAME>END_PI", original_estimate: 0} Api.create_task gon.project_id, task, (task) => @tasks.push task @notify() removeTasks: (tasks) -> @removeTask(task) for task in tasks @notify() addTask: (item) -> @tasks.push(item) updateTask: (item) -> task = @getTask(item.id) task.name = item.name task.description = item.description task.tag_list = item.tag_list task.assignee_id = item.assignee_id task.original_estimate = item.original_estimate task.remaining_estimate = item.remaining_estimate task.delta = item.delta Api.update_task gon.project_id, item.id, item, (task) => @getTask(task.id).updated_at = task.updated_at @notify() removeTask: (item) -> Api.delete_task gon.project_id, item.id index = @tasks.indexOf(item) @tasks.splice(index, 1) getTask: (id) -> found = @tasks.where id:id if found.length > 0 then found[0] else null getTaskAt: (index) -> @tasks[index] setTask: (tasks) -> @tasks = tasks filterTasks: (tasks, filter = '', displayCompleted = true) -> data = tasks if filter.length > 0 filter = filter.toLowerCase() filtered = [] for task in data addIt = task.code.toLowerCase().indexOf(filter) > -1 if !addIt addIt = task.name.toLowerCase().indexOf(filter) > -1 if !addIt tags = task.tag_list.split(',') for tag in tags tag = $.trim(tag) if tag.toLowerCase().indexOf(filter) > -1 addIt = true break if !addIt found = @members.where user_id:task.assignee_id addIt = found.length > 0 && found[0].username.toLowerCase().indexOf(filter) > -1 filtered.push(task) if addIt data = filtered if !displayCompleted filtered = [] for task in data if task.remaining_estimate > 0 or task.original_estimate == 0 filtered.push(task) data = filtered data sortTasks: (tasks, key, order) -> tasks.sort (a,b) -> m = if order == 'asc' then 1 else -1 return -1 * m if a[key] < b[key] return +1 * m if a[key] > b[key] return 0 loadMembers: (callback) -> Api.project_members gon.project_id, (members) => @members = members if gon.can_update_tasks @selectableMembers = members else found = @members.where user_id:gon.user_id @selectableMembers = found callback() findUsername: (user_id) -> found = @members.where user_id:user_id if found.length > 0 then found[0].username else null canChangeAssignee: (task) -> resu = false logged = task.work_logged if logged == 0 if gon.can_take_unassigned_task && !gon.can_update_tasks resu = task.assignee_id == "" or task.assignee_id == null or parseInt(task.assignee_id) == gon.user_id else resu = gon.can_update_tasks resu
[ { "context": ".f-c-js-atoms-placement-label')\n else if key == 'perex'\n $setting = $('.f-c-js-atoms-placement-perex'", "end": 1938, "score": 0.952973484992981, "start": 1933, "tag": "KEY", "value": "perex" } ]
app/assets/javascripts/folio/console/modules/simple-form-with-atoms.coffee
sinfin/folio
4
sendMessage = (data) -> $('.f-c-simple-form-with-atoms__iframe, .f-c-merges-form-row__atoms-iframe').each -> @contentWindow.postMessage(data, window.origin) $(document) .one 'click', '.f-c-simple-form-with-atoms__form', (e) -> $('.f-c-simple-form-with-atoms').addClass('f-c-simple-form-with-atoms--expanded-form') .on 'submit', '.f-c-simple-form-with-atoms', (e) -> $(this).addClass('f-c-simple-form-with-atoms--submitting') .on 'click', '.f-c-simple-form-with-atoms__overlay-dismiss', (e) -> e.preventDefault() window.postMessage({ type: 'closeForm' }, window.origin) .on 'click', '.f-c-simple-form-with-atoms__form-toggle, .f-c-simple-form-with-atoms__title--clickable', (e) -> e.preventDefault() $('.f-c-simple-form-with-atoms').toggleClass('f-c-simple-form-with-atoms--expanded-form') .on 'keyup', '.f-c-js-atoms-placement-label', (e) -> e.preventDefault() $this = $(this) sendMessage type: 'updateLabel' locale: $this.data('locale') or null value: $this.val() .on 'keyup', '.f-c-js-atoms-placement-perex', (e) -> e.preventDefault() $this = $(this) sendMessage type: 'updatePerex' locale: $this.data('locale') or null value: $this.val() .on 'change folioCustomChange', '.f-c-js-atoms-placement-setting', (e) -> window.postMessage({ type: 'refreshPreview' }, window.origin) # used to refresh react select async options window.setTimeout (-> $(document).trigger('folioAtomSettingChanged')), 0 selectTab = ($el) -> $tab = $el.closest('.tab-pane') if $tab.length and !$tab.hasClass('active') id = $tab.attr('id') $('.nav-tabs .nav-link').filter(-> @href.split('#').pop() is id).click() editSetting = (locale, key) -> $('.f-c-simple-form-with-atoms').addClass('f-c-simple-form-with-atoms--expanded-form') if key == 'label' $setting = $('.f-c-js-atoms-placement-label') else if key == 'perex' $setting = $('.f-c-js-atoms-placement-perex') else $setting = $('.f-c-js-atoms-placement-setting').filter("[data-atom-setting='#{key}']") $setting = $setting.filter("[data-locale='#{locale}']") if locale if $setting.length selectTab($setting) $scroll = $setting.closest('.f-c-simple-form-with-atoms__scroll') callback = -> setTimeout((-> $setting.addClass('f-c-js-atoms-placement-setting--highlighted')), 0) setTimeout((-> $setting.removeClass('f-c-js-atoms-placement-setting--highlighted')), 300) if $setting.hasClass('selectized') $setting[0].selectize.focus() else if $setting.hasClass('redactor-source') $R($setting[0], 'editor.startFocus') else $setting.focus() if $scroll.scrollTop() > $(window).height() / 2 $scroll.animate scrollTop: 0, callback else callback() setHeight = -> $iframes = $('.f-c-simple-form-with-atoms__iframe, .f-c-merges-form-row__atoms-iframe') minHeight = 0 $iframes.each -> return unless @contentWindow.jQuery height = @contentWindow.jQuery('.f-c-atoms-previews').outerHeight(true) minHeight = Math.max(minHeight, height) if typeof height is 'number' $iframes.css('min-height', minHeight) receiveMessage = (e) -> return if e.origin isnt window.origin switch e.data.type when 'setHeight' then setHeight() when 'editSetting' then editSetting(e.data.locale, e.data.setting) window.addEventListener('message', receiveMessage, false)
154948
sendMessage = (data) -> $('.f-c-simple-form-with-atoms__iframe, .f-c-merges-form-row__atoms-iframe').each -> @contentWindow.postMessage(data, window.origin) $(document) .one 'click', '.f-c-simple-form-with-atoms__form', (e) -> $('.f-c-simple-form-with-atoms').addClass('f-c-simple-form-with-atoms--expanded-form') .on 'submit', '.f-c-simple-form-with-atoms', (e) -> $(this).addClass('f-c-simple-form-with-atoms--submitting') .on 'click', '.f-c-simple-form-with-atoms__overlay-dismiss', (e) -> e.preventDefault() window.postMessage({ type: 'closeForm' }, window.origin) .on 'click', '.f-c-simple-form-with-atoms__form-toggle, .f-c-simple-form-with-atoms__title--clickable', (e) -> e.preventDefault() $('.f-c-simple-form-with-atoms').toggleClass('f-c-simple-form-with-atoms--expanded-form') .on 'keyup', '.f-c-js-atoms-placement-label', (e) -> e.preventDefault() $this = $(this) sendMessage type: 'updateLabel' locale: $this.data('locale') or null value: $this.val() .on 'keyup', '.f-c-js-atoms-placement-perex', (e) -> e.preventDefault() $this = $(this) sendMessage type: 'updatePerex' locale: $this.data('locale') or null value: $this.val() .on 'change folioCustomChange', '.f-c-js-atoms-placement-setting', (e) -> window.postMessage({ type: 'refreshPreview' }, window.origin) # used to refresh react select async options window.setTimeout (-> $(document).trigger('folioAtomSettingChanged')), 0 selectTab = ($el) -> $tab = $el.closest('.tab-pane') if $tab.length and !$tab.hasClass('active') id = $tab.attr('id') $('.nav-tabs .nav-link').filter(-> @href.split('#').pop() is id).click() editSetting = (locale, key) -> $('.f-c-simple-form-with-atoms').addClass('f-c-simple-form-with-atoms--expanded-form') if key == 'label' $setting = $('.f-c-js-atoms-placement-label') else if key == '<KEY>' $setting = $('.f-c-js-atoms-placement-perex') else $setting = $('.f-c-js-atoms-placement-setting').filter("[data-atom-setting='#{key}']") $setting = $setting.filter("[data-locale='#{locale}']") if locale if $setting.length selectTab($setting) $scroll = $setting.closest('.f-c-simple-form-with-atoms__scroll') callback = -> setTimeout((-> $setting.addClass('f-c-js-atoms-placement-setting--highlighted')), 0) setTimeout((-> $setting.removeClass('f-c-js-atoms-placement-setting--highlighted')), 300) if $setting.hasClass('selectized') $setting[0].selectize.focus() else if $setting.hasClass('redactor-source') $R($setting[0], 'editor.startFocus') else $setting.focus() if $scroll.scrollTop() > $(window).height() / 2 $scroll.animate scrollTop: 0, callback else callback() setHeight = -> $iframes = $('.f-c-simple-form-with-atoms__iframe, .f-c-merges-form-row__atoms-iframe') minHeight = 0 $iframes.each -> return unless @contentWindow.jQuery height = @contentWindow.jQuery('.f-c-atoms-previews').outerHeight(true) minHeight = Math.max(minHeight, height) if typeof height is 'number' $iframes.css('min-height', minHeight) receiveMessage = (e) -> return if e.origin isnt window.origin switch e.data.type when 'setHeight' then setHeight() when 'editSetting' then editSetting(e.data.locale, e.data.setting) window.addEventListener('message', receiveMessage, false)
true
sendMessage = (data) -> $('.f-c-simple-form-with-atoms__iframe, .f-c-merges-form-row__atoms-iframe').each -> @contentWindow.postMessage(data, window.origin) $(document) .one 'click', '.f-c-simple-form-with-atoms__form', (e) -> $('.f-c-simple-form-with-atoms').addClass('f-c-simple-form-with-atoms--expanded-form') .on 'submit', '.f-c-simple-form-with-atoms', (e) -> $(this).addClass('f-c-simple-form-with-atoms--submitting') .on 'click', '.f-c-simple-form-with-atoms__overlay-dismiss', (e) -> e.preventDefault() window.postMessage({ type: 'closeForm' }, window.origin) .on 'click', '.f-c-simple-form-with-atoms__form-toggle, .f-c-simple-form-with-atoms__title--clickable', (e) -> e.preventDefault() $('.f-c-simple-form-with-atoms').toggleClass('f-c-simple-form-with-atoms--expanded-form') .on 'keyup', '.f-c-js-atoms-placement-label', (e) -> e.preventDefault() $this = $(this) sendMessage type: 'updateLabel' locale: $this.data('locale') or null value: $this.val() .on 'keyup', '.f-c-js-atoms-placement-perex', (e) -> e.preventDefault() $this = $(this) sendMessage type: 'updatePerex' locale: $this.data('locale') or null value: $this.val() .on 'change folioCustomChange', '.f-c-js-atoms-placement-setting', (e) -> window.postMessage({ type: 'refreshPreview' }, window.origin) # used to refresh react select async options window.setTimeout (-> $(document).trigger('folioAtomSettingChanged')), 0 selectTab = ($el) -> $tab = $el.closest('.tab-pane') if $tab.length and !$tab.hasClass('active') id = $tab.attr('id') $('.nav-tabs .nav-link').filter(-> @href.split('#').pop() is id).click() editSetting = (locale, key) -> $('.f-c-simple-form-with-atoms').addClass('f-c-simple-form-with-atoms--expanded-form') if key == 'label' $setting = $('.f-c-js-atoms-placement-label') else if key == 'PI:KEY:<KEY>END_PI' $setting = $('.f-c-js-atoms-placement-perex') else $setting = $('.f-c-js-atoms-placement-setting').filter("[data-atom-setting='#{key}']") $setting = $setting.filter("[data-locale='#{locale}']") if locale if $setting.length selectTab($setting) $scroll = $setting.closest('.f-c-simple-form-with-atoms__scroll') callback = -> setTimeout((-> $setting.addClass('f-c-js-atoms-placement-setting--highlighted')), 0) setTimeout((-> $setting.removeClass('f-c-js-atoms-placement-setting--highlighted')), 300) if $setting.hasClass('selectized') $setting[0].selectize.focus() else if $setting.hasClass('redactor-source') $R($setting[0], 'editor.startFocus') else $setting.focus() if $scroll.scrollTop() > $(window).height() / 2 $scroll.animate scrollTop: 0, callback else callback() setHeight = -> $iframes = $('.f-c-simple-form-with-atoms__iframe, .f-c-merges-form-row__atoms-iframe') minHeight = 0 $iframes.each -> return unless @contentWindow.jQuery height = @contentWindow.jQuery('.f-c-atoms-previews').outerHeight(true) minHeight = Math.max(minHeight, height) if typeof height is 'number' $iframes.css('min-height', minHeight) receiveMessage = (e) -> return if e.origin isnt window.origin switch e.data.type when 'setHeight' then setHeight() when 'editSetting' then editSetting(e.data.locale, e.data.setting) window.addEventListener('message', receiveMessage, false)
[ { "context": "elayed-runners'\n\nDEVICES_WITH_TOKEN = ['email', 'xmpp', 'sms', 'telegram', 'matrix']\nSEND_GUARD = 10000", "end": 250, "score": 0.47303012013435364, "start": 247, "tag": "KEY", "value": "mpp" } ]
app/components/tfa/enter-token.coffee
melis-wallet/melis-cm-client
1
import Component from '@ember/component' import { validator, buildValidations } from 'ember-cp-validations' import { task } from 'ember-concurrency' import { waitTime } from 'melis-cm-svcs/utils/delayed-runners' DEVICES_WITH_TOKEN = ['email', 'xmpp', 'sms', 'telegram', 'matrix'] SEND_GUARD = 10000 Validations = buildValidations( token: [ validator('presence', true) validator('length', min: 5, max: 8) validator('number', allowString: true, integer: true) ] ) EnterToken = Component.extend(Validations, device: null token: null sendButton: false tokenSent: false running: false done: false isDisabled: ( -> @get('running') || @get('done') ).property('running', 'done') showSendButton: ( -> @get('sendButton') && DEVICES_WITH_TOKEN.includes(@get('device.name')) ).property('sendButton') showForm: ( -> @get('tokenSent') || !@get('showSendButton') ).property('tokenSent', 'showSendButton') sendToken: task( -> if device = @get('device') @set('tokenSent', true) @sendAction('on-send-token', device) yield waitTime(SEND_GUARD) ).drop() actions: sendToken: -> @get('sendToken').perform() enterToken: -> if @get('validations.isValid') && (token = @get('token')) && (device = @get('device')) @sendAction('on-valid-token', device, token) ) export default EnterToken
143166
import Component from '@ember/component' import { validator, buildValidations } from 'ember-cp-validations' import { task } from 'ember-concurrency' import { waitTime } from 'melis-cm-svcs/utils/delayed-runners' DEVICES_WITH_TOKEN = ['email', 'x<KEY>', 'sms', 'telegram', 'matrix'] SEND_GUARD = 10000 Validations = buildValidations( token: [ validator('presence', true) validator('length', min: 5, max: 8) validator('number', allowString: true, integer: true) ] ) EnterToken = Component.extend(Validations, device: null token: null sendButton: false tokenSent: false running: false done: false isDisabled: ( -> @get('running') || @get('done') ).property('running', 'done') showSendButton: ( -> @get('sendButton') && DEVICES_WITH_TOKEN.includes(@get('device.name')) ).property('sendButton') showForm: ( -> @get('tokenSent') || !@get('showSendButton') ).property('tokenSent', 'showSendButton') sendToken: task( -> if device = @get('device') @set('tokenSent', true) @sendAction('on-send-token', device) yield waitTime(SEND_GUARD) ).drop() actions: sendToken: -> @get('sendToken').perform() enterToken: -> if @get('validations.isValid') && (token = @get('token')) && (device = @get('device')) @sendAction('on-valid-token', device, token) ) export default EnterToken
true
import Component from '@ember/component' import { validator, buildValidations } from 'ember-cp-validations' import { task } from 'ember-concurrency' import { waitTime } from 'melis-cm-svcs/utils/delayed-runners' DEVICES_WITH_TOKEN = ['email', 'xPI:KEY:<KEY>END_PI', 'sms', 'telegram', 'matrix'] SEND_GUARD = 10000 Validations = buildValidations( token: [ validator('presence', true) validator('length', min: 5, max: 8) validator('number', allowString: true, integer: true) ] ) EnterToken = Component.extend(Validations, device: null token: null sendButton: false tokenSent: false running: false done: false isDisabled: ( -> @get('running') || @get('done') ).property('running', 'done') showSendButton: ( -> @get('sendButton') && DEVICES_WITH_TOKEN.includes(@get('device.name')) ).property('sendButton') showForm: ( -> @get('tokenSent') || !@get('showSendButton') ).property('tokenSent', 'showSendButton') sendToken: task( -> if device = @get('device') @set('tokenSent', true) @sendAction('on-send-token', device) yield waitTime(SEND_GUARD) ).drop() actions: sendToken: -> @get('sendToken').perform() enterToken: -> if @get('validations.isValid') && (token = @get('token')) && (device = @get('device')) @sendAction('on-valid-token', device, token) ) export default EnterToken
[ { "context": "ypto.randomBytes(16), \"utf8\"\n\n token = md5.digest \"base64\"\n response.cookie \"XSRF-TOKEN\", token\n", "end": 3055, "score": 0.6652007699012756, "start": 3045, "tag": "PASSWORD", "value": "md5.digest" }, { "context": "---------------------------------\n# Copyright 2014 Patrick Mueller\n#\n# Licensed under the Apache License, Version 2.", "end": 3880, "score": 0.9998345375061035, "start": 3865, "tag": "NAME", "value": "Patrick Mueller" } ]
lib-src/server.coffee
pmuellr/gh-miner
1
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" crypto = require "crypto" _ = require "underscore" ports = require "ports" express = require "express" passport = require "passport" ppGithub = require "passport-github" pkg = require "../package.json" utils = require "./utils" #------------------------------------------------------------------------------- PROGRAM = pkg.name WWW_DIR = path.join __dirname, "..", "www" DEFAULT_OPTIONS = cookieSecret: "stupid cookie secret for #{PROGRAM}" port: ports.getPort PROGRAM verbose: false #------------------------------------------------------------------------------- exports.run = (options) -> options = _.defaults options, DEFAULT_OPTIONS utils.setVerbose options.verbose utils.logv "options: #{JSON.stringify options, null, 4}" # main app app = express() app.use express.cookieParser() app.use express.cookieSession {secret: options.cookieSecret} app.use setXSRFcookie # app.use express.logger() # app.use dumpRequest "app" app.use gzipify WWW_DIR app.use "/", express.static WWW_DIR console.log "server starting: http://localhost:#{options.port}" app.listen options.port #------------------------------------------------------------------------------- dirFromRoot = (dir) -> path.resolve __dirname, "..", dir #------------------------------------------------------------------------------- dumpRequest = (title) -> (request, response, next) -> console.log "dumpRequest #{title}" console.log " path: ", request.path next() #-------------------------------------------- gzExists = {} gzipify = (dir) -> (request, response, next) -> gzFile = path.join "www", "gz#{request.url}" unless gzExists[gzFile]? if fs.existsSync gzFile stats = fs.statSync gzFile gzExists[gzFile] = true if stats.isFile() return next() unless gzExists[gzFile] response.set "Content-Encoding", "gzip" setVary response, "Accept-Encoding" request.url = "/gz#{request.url}" next() #-------------------------------------------- setVary = (response, newToken) -> varyHeader = response.get("Vary") || "" if "" is varyHeader vary = "Accept-Encoding" else if -1 is vary.indexOf "Accept-Encoding" vary = "#{vary}, Accept-Encoding" response.set "Vary", vary if vary? #------------------------------------------------------------------------------- setXSRFcookie = (request, response, next) -> token = request.session.xsrfToken if token? response.cookie "XSRF-TOKEN", token next() return session = JSON.stringify request.session md5 = crypto.createHash "md5" md5.update crypto.randomBytes(16), "utf8" md5.update JSON.stringify(request.session), "utf8" md5.update crypto.randomBytes(16), "utf8" token = md5.digest "base64" response.cookie "XSRF-TOKEN", token request.session.xsrfToken = token next() #------------------------------------------------------------------------------- checkXSRFheader = (request, response, next) -> headerToken = request.headers["x-xsrf-token"] || "" # if headerToken is "" # response.send 400, "no XSRF token in X-XSRF-TOKEN header" # return sessionToken = request.session.xsrfToken # unless headerToken is sessionToken # response.send 400, "invalid XSRF token in X-XSRF-TOKEN header" # return next() #------------------------------------------------------------------------------- exports.run() if require.main is module #------------------------------------------------------------------------------- # Copyright 2014 Patrick Mueller # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
76401
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" crypto = require "crypto" _ = require "underscore" ports = require "ports" express = require "express" passport = require "passport" ppGithub = require "passport-github" pkg = require "../package.json" utils = require "./utils" #------------------------------------------------------------------------------- PROGRAM = pkg.name WWW_DIR = path.join __dirname, "..", "www" DEFAULT_OPTIONS = cookieSecret: "stupid cookie secret for #{PROGRAM}" port: ports.getPort PROGRAM verbose: false #------------------------------------------------------------------------------- exports.run = (options) -> options = _.defaults options, DEFAULT_OPTIONS utils.setVerbose options.verbose utils.logv "options: #{JSON.stringify options, null, 4}" # main app app = express() app.use express.cookieParser() app.use express.cookieSession {secret: options.cookieSecret} app.use setXSRFcookie # app.use express.logger() # app.use dumpRequest "app" app.use gzipify WWW_DIR app.use "/", express.static WWW_DIR console.log "server starting: http://localhost:#{options.port}" app.listen options.port #------------------------------------------------------------------------------- dirFromRoot = (dir) -> path.resolve __dirname, "..", dir #------------------------------------------------------------------------------- dumpRequest = (title) -> (request, response, next) -> console.log "dumpRequest #{title}" console.log " path: ", request.path next() #-------------------------------------------- gzExists = {} gzipify = (dir) -> (request, response, next) -> gzFile = path.join "www", "gz#{request.url}" unless gzExists[gzFile]? if fs.existsSync gzFile stats = fs.statSync gzFile gzExists[gzFile] = true if stats.isFile() return next() unless gzExists[gzFile] response.set "Content-Encoding", "gzip" setVary response, "Accept-Encoding" request.url = "/gz#{request.url}" next() #-------------------------------------------- setVary = (response, newToken) -> varyHeader = response.get("Vary") || "" if "" is varyHeader vary = "Accept-Encoding" else if -1 is vary.indexOf "Accept-Encoding" vary = "#{vary}, Accept-Encoding" response.set "Vary", vary if vary? #------------------------------------------------------------------------------- setXSRFcookie = (request, response, next) -> token = request.session.xsrfToken if token? response.cookie "XSRF-TOKEN", token next() return session = JSON.stringify request.session md5 = crypto.createHash "md5" md5.update crypto.randomBytes(16), "utf8" md5.update JSON.stringify(request.session), "utf8" md5.update crypto.randomBytes(16), "utf8" token = <PASSWORD> "base64" response.cookie "XSRF-TOKEN", token request.session.xsrfToken = token next() #------------------------------------------------------------------------------- checkXSRFheader = (request, response, next) -> headerToken = request.headers["x-xsrf-token"] || "" # if headerToken is "" # response.send 400, "no XSRF token in X-XSRF-TOKEN header" # return sessionToken = request.session.xsrfToken # unless headerToken is sessionToken # response.send 400, "invalid XSRF token in X-XSRF-TOKEN header" # return next() #------------------------------------------------------------------------------- exports.run() if require.main is module #------------------------------------------------------------------------------- # Copyright 2014 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" crypto = require "crypto" _ = require "underscore" ports = require "ports" express = require "express" passport = require "passport" ppGithub = require "passport-github" pkg = require "../package.json" utils = require "./utils" #------------------------------------------------------------------------------- PROGRAM = pkg.name WWW_DIR = path.join __dirname, "..", "www" DEFAULT_OPTIONS = cookieSecret: "stupid cookie secret for #{PROGRAM}" port: ports.getPort PROGRAM verbose: false #------------------------------------------------------------------------------- exports.run = (options) -> options = _.defaults options, DEFAULT_OPTIONS utils.setVerbose options.verbose utils.logv "options: #{JSON.stringify options, null, 4}" # main app app = express() app.use express.cookieParser() app.use express.cookieSession {secret: options.cookieSecret} app.use setXSRFcookie # app.use express.logger() # app.use dumpRequest "app" app.use gzipify WWW_DIR app.use "/", express.static WWW_DIR console.log "server starting: http://localhost:#{options.port}" app.listen options.port #------------------------------------------------------------------------------- dirFromRoot = (dir) -> path.resolve __dirname, "..", dir #------------------------------------------------------------------------------- dumpRequest = (title) -> (request, response, next) -> console.log "dumpRequest #{title}" console.log " path: ", request.path next() #-------------------------------------------- gzExists = {} gzipify = (dir) -> (request, response, next) -> gzFile = path.join "www", "gz#{request.url}" unless gzExists[gzFile]? if fs.existsSync gzFile stats = fs.statSync gzFile gzExists[gzFile] = true if stats.isFile() return next() unless gzExists[gzFile] response.set "Content-Encoding", "gzip" setVary response, "Accept-Encoding" request.url = "/gz#{request.url}" next() #-------------------------------------------- setVary = (response, newToken) -> varyHeader = response.get("Vary") || "" if "" is varyHeader vary = "Accept-Encoding" else if -1 is vary.indexOf "Accept-Encoding" vary = "#{vary}, Accept-Encoding" response.set "Vary", vary if vary? #------------------------------------------------------------------------------- setXSRFcookie = (request, response, next) -> token = request.session.xsrfToken if token? response.cookie "XSRF-TOKEN", token next() return session = JSON.stringify request.session md5 = crypto.createHash "md5" md5.update crypto.randomBytes(16), "utf8" md5.update JSON.stringify(request.session), "utf8" md5.update crypto.randomBytes(16), "utf8" token = PI:PASSWORD:<PASSWORD>END_PI "base64" response.cookie "XSRF-TOKEN", token request.session.xsrfToken = token next() #------------------------------------------------------------------------------- checkXSRFheader = (request, response, next) -> headerToken = request.headers["x-xsrf-token"] || "" # if headerToken is "" # response.send 400, "no XSRF token in X-XSRF-TOKEN header" # return sessionToken = request.session.xsrfToken # unless headerToken is sessionToken # response.send 400, "invalid XSRF token in X-XSRF-TOKEN header" # return next() #------------------------------------------------------------------------------- exports.run() if require.main is module #------------------------------------------------------------------------------- # Copyright 2014 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
[ { "context": "tion generator command\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\n\nfs = require('fs')\ngenerate = require(", "end": 95, "score": 0.9998855590820312, "start": 78, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
cli/commands/docs.coffee
lovely-io/lovely.io-stl
2
# # Automatic api-documentation generator command # # Copyright (C) 2011-2012 Nikolay Nemshilov # fs = require('fs') generate = require('../documentation') cwd = process.cwd() docs = 'docs/' overwrite = false index = [] # # Generates docs from a coffee-script file # # @param {String} filename # generate_docs_for = (filename)-> doc_file = "#{cwd}/#{docs}#{filename.replace(/^src\//, '')}.md" doc_dir = doc_file.replace(/\/[^\/]+$/, '') index.push(doc_file) sout (" ■ ".yellow + filename + ' ').ljust(60, '.') + ' ' return sout("Already exists\n".yellow) if fs.existsSync(doc_file) fs.mkdirSync(doc_dir, 0o0755) unless fs.existsSync(doc_dir) content = generate.from_file("#{cwd}/#{filename}") return sout("Not supported yet".yellow) if content is false fs.writeFileSync(doc_file, content) sout "Ok\n".green # # Recoursively loops through the source directory # # @param {String} dirname # loop_directory_recursively = (dirname)-> for filename in fs.readdirSync("#{cwd}/#{dirname}") if fs.statSync("#{cwd}/#{dirname}/#{filename}").isDirectory() loop_directory_recursively("#{dirname}/#{filename}") else generate_docs_for("#{dirname}/#{filename}") # # Kicks in the documentation generator # exports.init = (args) -> docs_dir = "#{cwd}/#{docs}" build_docs = -> sout (" • ".grey + "Creating the "+ docs.yellow + " directory ").ljust(70, '.') + " " if fs.existsSync(docs_dir) sout "Already exists\n".yellow else fs.mkdirSync(docs_dir, 0o0755); sout "Ok\n".green print " • ".grey + "Generating documentation from sources" generate_docs_for('main.coffee') if fs.existsSync('main.coffee') generate_docs_for('main.js') if fs.existsSync('main.js') loop_directory_recursively('src') print "\nDONE".green print "Generating the API docs for the project\n".magenta if args.indexOf('rebuild') isnt -1 sout (" • ".grey + "Deleting the "+ docs.yellow + " directory ").ljust(70, '.') + " " system "rm -rf #{docs_dir}", -> sout "Ok\n".green build_docs() else build_docs() # # Prints out the help # exports.help = (args) -> """ Automatic API-documentation generator Usage: lovely docs[ rebuild] If you want to erase and rebuild the current docs folder call lovely docs rebuild """
91926
# # Automatic api-documentation generator command # # Copyright (C) 2011-2012 <NAME> # fs = require('fs') generate = require('../documentation') cwd = process.cwd() docs = 'docs/' overwrite = false index = [] # # Generates docs from a coffee-script file # # @param {String} filename # generate_docs_for = (filename)-> doc_file = "#{cwd}/#{docs}#{filename.replace(/^src\//, '')}.md" doc_dir = doc_file.replace(/\/[^\/]+$/, '') index.push(doc_file) sout (" ■ ".yellow + filename + ' ').ljust(60, '.') + ' ' return sout("Already exists\n".yellow) if fs.existsSync(doc_file) fs.mkdirSync(doc_dir, 0o0755) unless fs.existsSync(doc_dir) content = generate.from_file("#{cwd}/#{filename}") return sout("Not supported yet".yellow) if content is false fs.writeFileSync(doc_file, content) sout "Ok\n".green # # Recoursively loops through the source directory # # @param {String} dirname # loop_directory_recursively = (dirname)-> for filename in fs.readdirSync("#{cwd}/#{dirname}") if fs.statSync("#{cwd}/#{dirname}/#{filename}").isDirectory() loop_directory_recursively("#{dirname}/#{filename}") else generate_docs_for("#{dirname}/#{filename}") # # Kicks in the documentation generator # exports.init = (args) -> docs_dir = "#{cwd}/#{docs}" build_docs = -> sout (" • ".grey + "Creating the "+ docs.yellow + " directory ").ljust(70, '.') + " " if fs.existsSync(docs_dir) sout "Already exists\n".yellow else fs.mkdirSync(docs_dir, 0o0755); sout "Ok\n".green print " • ".grey + "Generating documentation from sources" generate_docs_for('main.coffee') if fs.existsSync('main.coffee') generate_docs_for('main.js') if fs.existsSync('main.js') loop_directory_recursively('src') print "\nDONE".green print "Generating the API docs for the project\n".magenta if args.indexOf('rebuild') isnt -1 sout (" • ".grey + "Deleting the "+ docs.yellow + " directory ").ljust(70, '.') + " " system "rm -rf #{docs_dir}", -> sout "Ok\n".green build_docs() else build_docs() # # Prints out the help # exports.help = (args) -> """ Automatic API-documentation generator Usage: lovely docs[ rebuild] If you want to erase and rebuild the current docs folder call lovely docs rebuild """
true
# # Automatic api-documentation generator command # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # fs = require('fs') generate = require('../documentation') cwd = process.cwd() docs = 'docs/' overwrite = false index = [] # # Generates docs from a coffee-script file # # @param {String} filename # generate_docs_for = (filename)-> doc_file = "#{cwd}/#{docs}#{filename.replace(/^src\//, '')}.md" doc_dir = doc_file.replace(/\/[^\/]+$/, '') index.push(doc_file) sout (" ■ ".yellow + filename + ' ').ljust(60, '.') + ' ' return sout("Already exists\n".yellow) if fs.existsSync(doc_file) fs.mkdirSync(doc_dir, 0o0755) unless fs.existsSync(doc_dir) content = generate.from_file("#{cwd}/#{filename}") return sout("Not supported yet".yellow) if content is false fs.writeFileSync(doc_file, content) sout "Ok\n".green # # Recoursively loops through the source directory # # @param {String} dirname # loop_directory_recursively = (dirname)-> for filename in fs.readdirSync("#{cwd}/#{dirname}") if fs.statSync("#{cwd}/#{dirname}/#{filename}").isDirectory() loop_directory_recursively("#{dirname}/#{filename}") else generate_docs_for("#{dirname}/#{filename}") # # Kicks in the documentation generator # exports.init = (args) -> docs_dir = "#{cwd}/#{docs}" build_docs = -> sout (" • ".grey + "Creating the "+ docs.yellow + " directory ").ljust(70, '.') + " " if fs.existsSync(docs_dir) sout "Already exists\n".yellow else fs.mkdirSync(docs_dir, 0o0755); sout "Ok\n".green print " • ".grey + "Generating documentation from sources" generate_docs_for('main.coffee') if fs.existsSync('main.coffee') generate_docs_for('main.js') if fs.existsSync('main.js') loop_directory_recursively('src') print "\nDONE".green print "Generating the API docs for the project\n".magenta if args.indexOf('rebuild') isnt -1 sout (" • ".grey + "Deleting the "+ docs.yellow + " directory ").ljust(70, '.') + " " system "rm -rf #{docs_dir}", -> sout "Ok\n".green build_docs() else build_docs() # # Prints out the help # exports.help = (args) -> """ Automatic API-documentation generator Usage: lovely docs[ rebuild] If you want to erase and rebuild the current docs folder call lovely docs rebuild """